Example usage for org.hibernate.id IdentifierGenerator generate

List of usage examples for org.hibernate.id IdentifierGenerator generate

Introduction

In this page you can find the example usage for org.hibernate.id IdentifierGenerator generate.

Prototype

Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException;

Source Link

Document

Generate a new identifier.

Usage

From source file:com.aw.core.dao.bean.sql.BeanSqlBuilderUpdateImpl.java

License:Open Source License

protected Serializable generateIdentifier(final IdentifierGenerator identifierGenerator) {
    Serializable nuevoId = (Serializable) daoHbm.executeQuery(new DAOExecuter() {
        public Object execute(Connection connection) {
            SessionImplementor sessionImplementor = (SessionImplementor) daoHbm.getHSession();
            Serializable idSerializable = identifierGenerator.generate(sessionImplementor, null);
            return idSerializable;
        }/*  w ww  . ja  v a2s  .c o m*/
    });
    return nuevoId;
}

From source file:net.sf.beanlib.hibernate3.Hibernate3SequenceGenerator.java

License:Apache License

/** Returns the next sequence id from the specified sequence and session. */
public static long nextval(final String sequenceName, final Session session) {
    Object target = session;//from w ww . j a  v a  2 s.  c o  m

    if (Proxy.isProxyClass(session.getClass())) {
        // Dig out the underlying session.
        InvocationHandler invocationHandler = Proxy.getInvocationHandler(session);

        if (invocationHandler instanceof DtoCentricCloseSuppressingInvocationHandler) {
            // This is faster for we don't need to use reflection.
            DtoCentricCloseSuppressingInvocationHandler dch = (DtoCentricCloseSuppressingInvocationHandler) invocationHandler;
            target = dch.getTarget();
        } else {
            Class<?> invocationHandlerClass = invocationHandler.getClass();
            Class<?> invocationHandlerDeclaringClass = invocationHandlerClass.getDeclaringClass();

            if (invocationHandlerDeclaringClass == HibernateTemplate.class) {
                String className = invocationHandlerClass.getName();

                if (className.endsWith("CloseSuppressingInvocationHandler")) {
                    // Assume this is the private class org.springframework.orm.hibernate3.HibernateTempate$CloseSuppressingInvocationHandler
                    // Dig out the private target.  
                    // I know this is bad, but there doesn't seem to be a better way.  Oh well.
                    try {
                        Field f = invocationHandlerClass.getDeclaredField("target");
                        f.setAccessible(true);
                        target = f.get(invocationHandler);
                    } catch (SecurityException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchFieldException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }

                }
            }

        }
    }
    SessionImpl sessionImpl;

    if (target instanceof SessionImpl)
        sessionImpl = (SessionImpl) target;
    else
        throw new IllegalStateException("Not yet know how to handle the given session!");
    IdentifierGenerator idGenerator = createIdentifierGenerator(sequenceName, session);
    Serializable id = idGenerator.generate(sessionImpl, null);
    return (Long) id;
}

From source file:net.sf.beanlib.hibernate4.Hibernate4SequenceGenerator.java

License:Apache License

/** Returns the next sequence id from the specified sequence and session. */
public static long nextval(final String sequenceName, final Session session) {
    Object target = session;// w w w  .  jav a2 s  .  c  om

    // if (Proxy.isProxyClass(session.getClass()))
    // {
    // // Dig out the underlying session.
    // InvocationHandler invocationHandler = Proxy.getInvocationHandler(session);
    //
    // if (invocationHandler instanceof DtoCentricCloseSuppressingInvocationHandler)
    // {
    // // This is faster for we don't need to use reflection.
    // DtoCentricCloseSuppressingInvocationHandler dch =
    // (DtoCentricCloseSuppressingInvocationHandler)invocationHandler;
    // target = dch.getTarget();
    // }
    // else {
    // Class<?> invocationHandlerClass = invocationHandler.getClass();
    // Class<?> invocationHandlerDeclaringClass = invocationHandlerClass.getDeclaringClass();
    //
    // if (invocationHandlerDeclaringClass == HibernateTemplate.class)
    // {
    // String className = invocationHandlerClass.getName();
    //
    // if (className.endsWith("CloseSuppressingInvocationHandler"))
    // {
    // // Assume this is the private class
    // org.springframework.orm.hibernate3.HibernateTempate$CloseSuppressingInvocationHandler
    // // Dig out the private target.
    // // I know this is bad, but there doesn't seem to be a better way. Oh well.
    // try {
    // Field f = invocationHandlerClass.getDeclaredField("target");
    // f.setAccessible(true);
    // target = f.get(invocationHandler);
    // } catch (SecurityException e) {
    // throw new RuntimeException(e);
    // } catch (NoSuchFieldException e) {
    // throw new RuntimeException(e);
    // } catch (IllegalAccessException e) {
    // throw new RuntimeException(e);
    // }
    //
    // }
    // }
    //
    // }
    // }
    SessionImpl sessionImpl;

    if (target instanceof SessionImpl) {
        sessionImpl = (SessionImpl) target;
    } else {
        throw new IllegalStateException("Not yet know how to handle the given session!");
    }
    IdentifierGenerator idGenerator = createIdentifierGenerator(sequenceName, session);
    Serializable id = idGenerator.generate(sessionImpl, null);
    return (Long) id;
}

From source file:org.codekaizen.vtj.ids.hibernate3.ReflectiveVTUUIDIdentifierGeneratorTest.java

License:Open Source License

@Test
public void shouldGenerateNewValueIfObjectIdIsNull() {
    IdentifierGenerator generator = new ReflectiveVTUUIDIdentifierGenerator();
    SessionImplementor sessionImplementor = mock(SessionImplementor.class);
    ObjectIdEntity entity = new ObjectIdEntity();
    VTUUID id = (VTUUID) generator.generate(sessionImplementor, entity);
    assertNotNull(id);//from   www .  j a va  2  s . c  o  m
}

From source file:org.codekaizen.vtj.ids.hibernate3.ReflectiveVTUUIDIdentifierGeneratorTest.java

License:Open Source License

@Test
public void shouldUseCurrentValueIfObjectIdIsNotNull() {
    IdentifierGenerator generator = new ReflectiveVTUUIDIdentifierGenerator();
    SessionImplementor sessionImplementor = mock(SessionImplementor.class);
    ObjectIdEntity entity = new ObjectIdEntity();
    VTUUID id = (VTUUID) generator.generate(sessionImplementor, entity);
    assertNotNull(id);/*from  w w  w .  j  a v  a 2 s .  c  o  m*/
    entity.setObjectId(id);
    VTUUID nextId = (VTUUID) generator.generate(sessionImplementor, entity);
    assertTrue(nextId == id);
}

From source file:org.codekaizen.vtj.ids.hibernate3.ReflectiveVTUUIDIdentifierGeneratorTest.java

License:Open Source License

@Test
public void shouldGenerateNewValueIfIdIsNull() {
    IdentifierGenerator generator = new ReflectiveVTUUIDIdentifierGenerator();
    SessionImplementor sessionImplementor = mock(SessionImplementor.class);
    IdEntity entity = new IdEntity();
    VTUUID id = (VTUUID) generator.generate(sessionImplementor, entity);
    assertNotNull(id);//from  w w w. j a v a  2  s  . co  m
}

From source file:org.codekaizen.vtj.ids.hibernate3.ReflectiveVTUUIDIdentifierGeneratorTest.java

License:Open Source License

@Test
public void shouldUseCurrentValueIfIdIsNotNull() {
    IdentifierGenerator generator = new ReflectiveVTUUIDIdentifierGenerator();
    SessionImplementor sessionImplementor = mock(SessionImplementor.class);
    IdEntity entity = new IdEntity();
    VTUUID id = (VTUUID) generator.generate(sessionImplementor, entity);
    assertNotNull(id);//from   w w  w .j  a va  2 s . c om
    entity.setId(id);
    VTUUID nextId = (VTUUID) generator.generate(sessionImplementor, entity);
    assertTrue(nextId == id);
}

From source file:org.codekaizen.vtj.ids.hibernate3.ReflectiveVTUUIDIdentifierGeneratorTest.java

License:Open Source License

@Test
public void shouldGenerateNewValueIfNoIdGetters() {
    IdentifierGenerator generator = new ReflectiveVTUUIDIdentifierGenerator();
    SessionImplementor sessionImplementor = mock(SessionImplementor.class);
    Date entity = new Date();
    VTUUID id = (VTUUID) generator.generate(sessionImplementor, entity);
    assertNotNull(id);//  w  ww. ja  va  2s. co  m
}

From source file:org.hyperic.hq.appdef.server.session.CpropDAO.java

License:Open Source License

/**
 * Generate a new ID for a class of the given type.
 * //from ww  w. jav  a2  s. com
 * @param className the persisted class name, as per the .hbm descriptor:
 *                  e.g. org.hyperic.hq.appdef.server.session.CpropKey
 * @param o         The object which will be getting the new ID
 * 
 * @return an Integer id for the new object.  If your class uses Long IDs
 *         then that's too bad ... we'll have to write another method.
 */
private Integer generateId(String className, Object o) {
    SessionFactoryImplementor factImpl = (SessionFactoryImplementor) sessionFactory;
    IdentifierGenerator gen = factImpl.getIdentifierGenerator(className);
    SessionImplementor sessImpl = (SessionImplementor) factImpl.getCurrentSession();
    return (Integer) gen.generate(sessImpl, o);
}

From source file:org.hyperic.hq.measurement.server.session.MeasurementTemplateDAO.java

License:Open Source License

public void createTemplates(final String pluginName,
        final Map<MonitorableType, List<MonitorableMeasurementInfo>> toAdd) {
    final IdentifierGenerator tmplIdGenerator = ((SessionFactoryImpl) sessionFactory)
            .getEntityPersister(MeasurementTemplate.class.getName()).getIdentifierGenerator();

    final String templatesql = "INSERT INTO EAM_MEASUREMENT_TEMPL "
            + "(id, name, alias, units, collection_type, default_on, "
            + "default_interval, designate, monitorable_type_id, "
            + "category_id, template, plugin, ctime, mtime) "
            + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    final List<MonitorableMeasurementInfo> combinedInfos = new ArrayList<MonitorableMeasurementInfo>();
    for (List<MonitorableMeasurementInfo> info : toAdd.values()) {
        combinedInfos.addAll(info);/*  w w w.j  a v  a  2 s . co  m*/
    }
    final long current = System.currentTimeMillis();
    //We need JdbcTemplate to throw runtime Exception to roll back tx if batch update fails, else we'll get partial write
    jdbcTemplate.batchUpdate(templatesql, new BatchPreparedStatementSetter() {
        HashMap<String, Category> cats = new HashMap<String, Category>();

        public void setValues(PreparedStatement stmt, int i) throws SQLException {

            MeasurementInfo info = combinedInfos.get(i).getMeasurementInfo();
            Category cat = (Category) cats.get(info.getCategory());
            if (cat == null) {
                cat = catDAO.findByName(info.getCategory());
                if (cat == null) {
                    cat = catDAO.create(info.getCategory());
                }
                cats.put(info.getCategory(), cat);
            }
            Integer rawid = (Integer) tmplIdGenerator.generate((SessionImpl) getSession(),
                    new MeasurementTemplate());
            stmt.setInt(1, rawid.intValue());
            stmt.setString(2, info.getName());
            String alias = info.getAlias();
            if (alias.length() > ALIAS_LIMIT) {
                alias = alias.substring(0, ALIAS_LIMIT);
                log.warn("ALIAS field of EAM_MEASUREMENT_TEMPLATE truncated: original value was "
                        + info.getAlias() + ", truncated value is " + alias);
            }
            stmt.setString(3, alias);
            stmt.setString(4, info.getUnits());
            stmt.setInt(5, info.getCollectionType());
            stmt.setBoolean(6, info.isDefaultOn());
            stmt.setLong(7, info.getInterval());
            stmt.setBoolean(8, info.isIndicator());
            stmt.setInt(9, combinedInfos.get(i).getMonitorableType().getId().intValue());
            stmt.setInt(10, cat.getId().intValue());
            stmt.setString(11, info.getTemplate());
            stmt.setString(12, pluginName);
            stmt.setLong(13, current);
            stmt.setLong(14, current);
        }

        public int getBatchSize() {
            return combinedInfos.size();
        }
    });
}