Java Code Examples for org.hibernate.metadata.ClassMetadata

The following examples show how to use org.hibernate.metadata.ClassMetadata. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
private boolean copyState(Object entity, Type[] types, Object[] state, SessionFactory sf) {
	// copy the entity state into the state array and return true if the state has changed
	ClassMetadata metadata = sf.getClassMetadata( entity.getClass() );
	Object[] newState = metadata.getPropertyValues( entity );
	int size = newState.length;
	boolean isDirty = false;
	for ( int index = 0; index < size; index++ ) {
		if ( ( state[index] == LazyPropertyInitializer.UNFETCHED_PROPERTY &&
				newState[index] != LazyPropertyInitializer.UNFETCHED_PROPERTY ) ||
				( state[index] != newState[index] && !types[index].isEqual( state[index], newState[index] ) ) ) {
			isDirty = true;
			state[index] = newState[index];
		}
	}
	return isDirty;
}
 
Example #2
Source Project: uyuni   Author: uyuni-project   File: HibernateFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Util to reload an object using Hibernate
 * @param obj to be reloaded
 * @return Object found if not, null
 * @throws HibernateException if something bad happens.
 */
public static Object reload(Object obj) throws HibernateException {
    // assertNotNull(obj);
    ClassMetadata cmd = connectionManager.getMetadata(obj);
    Serializable id = cmd.getIdentifier(obj, (SessionImplementor) getSession());
    Session session = getSession();
    session.flush();
    session.evict(obj);
    /*
     * In hibernate 3, the following doesn't work:
     * session.load(obj.getClass(), id);
     * load returns the proxy class instead of the persisted class, ie,
     * Filter$$EnhancerByCGLIB$$9bcc734d_2 instead of Filter.
     * session.get is set to not return the proxy class, so that is what we'll use.
     */
    // assertNotSame(obj, result);
    return session.get(obj.getClass(), id);
}
 
Example #3
Source Project: lams   Author: lamsfoundation   File: DefaultFlushEntityEventListener.java    License: GNU General Public License v2.0 6 votes vote down vote up
private boolean copyState(Object entity, Type[] types, Object[] state, SessionFactory sf) {
	// copy the entity state into the state array and return true if the state has changed
	ClassMetadata metadata = sf.getClassMetadata( entity.getClass() );
	Object[] newState = metadata.getPropertyValues( entity );
	int size = newState.length;
	boolean isDirty = false;
	for ( int index = 0; index < size; index++ ) {
		if ( ( state[index] == LazyPropertyInitializer.UNFETCHED_PROPERTY &&
				newState[index] != LazyPropertyInitializer.UNFETCHED_PROPERTY ) ||
				( state[index] != newState[index] && !types[index].isEqual( state[index], newState[index] ) ) ) {
			isDirty = true;
			state[index] = newState[index];
		}
	}
	return isDirty;
}
 
Example #4
Source Project: mycore   Author: MyCoRe-Org   File: MCRHibernateConfigHelper.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static void modifyConstraints(SessionFactoryImpl sessionFactoryImpl) {
    ClassMetadata classMetadata = sessionFactoryImpl.getClassMetadata(MCRCategoryImpl.class);
    AbstractEntityPersister aep = (AbstractEntityPersister) classMetadata;
    String qualifiedTableName = aep.getTableName();
    try (Session session = sessionFactoryImpl.openSession()) {
        session.doWork(connection -> {
            String updateStmt = Stream.of("ClassLeftUnique", "ClassRightUnique")
                .flatMap(idx -> Stream.of("drop constraint if exists " + idx,
                    String.format(Locale.ROOT, "add constraint %s unique (%s) deferrable initially deferred", idx,
                        getUniqueColumns(MCRCategoryImpl.class, idx))))
                .collect(Collectors.joining(", ", getAlterTableString(connection) + qualifiedTableName + " ", ""));
            try (Statement stmt = connection.createStatement()) {
                LogManager.getLogger().info("Fixing PostgreSQL Schema for {}:\n{}", qualifiedTableName, updateStmt);
                stmt.execute(updateStmt);
            }
        });
    }
}
 
Example #5
Source Project: jeewx   Author: zhangdaiscott   File: GenericBaseCommonDao.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取所有数据表
 * 
 * @return
 */
public List<DBTable> getAllDbTableName() {
	List<DBTable> resultList = new ArrayList<DBTable>();
	SessionFactory factory = getSession().getSessionFactory();
	Map<String, ClassMetadata> metaMap = factory.getAllClassMetadata();
	for (String key : (Set<String>) metaMap.keySet()) {
		DBTable dbTable = new DBTable();
		AbstractEntityPersister classMetadata = (AbstractEntityPersister) metaMap
				.get(key);
		dbTable.setTableName(classMetadata.getTableName());
		dbTable.setEntityName(classMetadata.getEntityName());
		Class<?> c;
		try {
			c = Class.forName(key);
			JeecgEntityTitle t = c.getAnnotation(JeecgEntityTitle.class);
			dbTable.setTableTitle(t != null ? t.name() : "");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		resultList.add(dbTable);
	}
	return resultList;
}
 
Example #6
Source Project: scheduling   Author: ow2-proactive   File: TestJobRemove.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private void checkAllEntitiesDeleted(String... skipClasses) {
    Set<String> skip = ImmutableSet.copyOf(skipClasses);

    Session session = dbManager.getSessionFactory().openSession();
    try {
        for (ClassMetadata metadata : session.getSessionFactory().getAllClassMetadata().values()) {
            if (!skip.contains(metadata.getEntityName())) {
                System.out.println("Check " + metadata.getEntityName());
                List<Object> list = session.createCriteria(metadata.getEntityName()).list();
                Assert.assertEquals("Unexpected " + metadata.getEntityName(), 0, list.size());
            }
        }
    } finally {
        session.close();
    }
}
 
Example #7
Source Project: spacewalk   Author: spacewalkproject   File: HibernateFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Util to reload an object using Hibernate
 * @param obj to be reloaded
 * @return Object found if not, null
 * @throws HibernateException if something bad happens.
 */
public static Object reload(Object obj) throws HibernateException {
    // assertNotNull(obj);
    ClassMetadata cmd = connectionManager.getMetadata(obj);
    Serializable id = cmd.getIdentifier(obj, EntityMode.POJO);
    Session session = getSession();
    session.flush();
    session.evict(obj);
    /*
     * In hibernate 3, the following doesn't work:
     * session.load(obj.getClass(), id);
     * load returns the proxy class instead of the persisted class, ie,
     * Filter$$EnhancerByCGLIB$$9bcc734d_2 instead of Filter.
     * session.get is set to not return the proxy class, so that is what we'll use.
     */
    // assertNotSame(obj, result);
    return session.get(obj.getClass(), id);
}
 
Example #8
Source Project: Lottery   Author: caipiao   File: HibernateBaseDao.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 将更新对象拷贝至实体对象,并处理many-to-one的更新。
 * 
 * @param updater
 * @param po
 */
private void updaterCopyToPersistentObject(Updater<T> updater, T po,
		ClassMetadata cm) {
	String[] propNames = cm.getPropertyNames();
	String identifierName = cm.getIdentifierPropertyName();
	T bean = updater.getBean();
	Object value;
	for (String propName : propNames) {
		if (propName.equals(identifierName)) {
			continue;
		}
		try {
			value = MyBeanUtils.getSimpleProperty(bean, propName);
			if (!updater.isUpdate(propName, value)) {
				continue;
			}
			cm.setPropertyValue(po, propName, value, POJO);
		} catch (Exception e) {
			throw new RuntimeException(
					"copy property to persistent object failed: '"
							+ propName + "'", e);
		}
	}
}
 
Example #9
Source Project: lemon   Author: xuhuisheng   File: HibernateBasicDao.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 取得对象的主键名,辅助函数.
 * 
 * @param entityClass
 *            实体类型
 * @return 主键名称
 */
public String getIdName(Class entityClass) {
    Assert.notNull(entityClass);
    entityClass = ReflectUtils.getOriginalClass(entityClass);

    ClassMetadata meta = this.getSessionFactory().getClassMetadata(
            entityClass);
    Assert.notNull(meta, "Class " + entityClass
            + " not define in hibernate session factory.");

    String idName = meta.getIdentifierPropertyName();
    Assert.hasText(idName, entityClass.getSimpleName()
            + " has no identifier property define.");

    return idName;
}
 
Example #10
/**
 * Construct a entity collection.
 *
 * @param parentMetadata parent meta data
 * @param childMetadata child meta data
 * @param parent parent object
 * @param objects child objects
 */
public HibernateEntityCollection(ClassMetadata parentMetadata, ClassMetadata childMetadata, Object parent,
		Collection<?> objects) {
	this.objects = objects;
	int i = 0;
	for (Type type : childMetadata.getPropertyTypes()) {
		if (type instanceof ManyToOneType) {
			ManyToOneType mto = (ManyToOneType) type;
			if (mto.getAssociatedEntityName().equals(parentMetadata.getEntityName())) {
				parentName = childMetadata.getPropertyNames()[i];
			}
		}
		i++;
	}
	this.metadata = childMetadata;
	this.parent = parent;
}
 
Example #11
@Test
public void testGetAttribute() throws LayerException {
	ClassMetadata metadata = factory.getClassMetadata(AbstractHibernateTestFeature.class);
	Attribute<?> attribute = featureModel.getAttribute(feature1, PARAM_INT_ATTR);
	Assert.assertNotNull(attribute);
	Assert.assertTrue(attribute instanceof IntegerAttribute);
	Assert.assertEquals(feature1.getIntAttr(), attribute.getValue());

	attribute = featureModel.getAttribute(feature1, PARAM_TEXT_ATTR);
	Assert.assertNotNull(attribute);
	Assert.assertTrue(attribute instanceof StringAttribute);
	Assert.assertEquals(feature1.getTextAttr(), attribute.getValue());

	attribute = featureModel.getAttribute(feature1, ATTR__MANY_TO_ONE__DOT__INT);
	Assert.assertNotNull(attribute);
	Assert.assertTrue(attribute instanceof IntegerAttribute);
	Assert.assertEquals(feature1.getManyToOne().getIntAttr(), attribute.getValue());

	attribute = featureModel.getAttribute(feature1, ATTR__MANY_TO_ONE__DOT__TEXT);
	Assert.assertNotNull(attribute);
	Assert.assertTrue(attribute instanceof StringAttribute);
	Assert.assertEquals(feature1.getManyToOne().getTextAttr(), attribute.getValue());

	// attribute = featureModel.getAttribute(feature1, PARAM_ONE_TO_MANY + HibernateLayerUtil.SEPARATOR
	// + PARAM_INT_ATTR + "[0]");
}
 
Example #12
Source Project: jeecg   Author: zhangdaiscott   File: GenericBaseCommonDao.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取所有数据表
 *
 * @return
 */
public List<DBTable> getAllDbTableName() {
	List<DBTable> resultList = new ArrayList<DBTable>();
	SessionFactory factory = getSession().getSessionFactory();
	Map<String, ClassMetadata> metaMap = factory.getAllClassMetadata();
	for (String key : (Set<String>) metaMap.keySet()) {
		DBTable dbTable = new DBTable();
		AbstractEntityPersister classMetadata = (AbstractEntityPersister) metaMap
				.get(key);
		dbTable.setTableName(classMetadata.getTableName());
		dbTable.setEntityName(classMetadata.getEntityName());
		Class<?> c;
		try {
			c = Class.forName(key);
			JeecgEntityTitle t = c.getAnnotation(JeecgEntityTitle.class);
			dbTable.setTableTitle(t != null ? t.name() : "");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		resultList.add(dbTable);
	}
	return resultList;
}
 
Example #13
Source Project: uyuni   Author: uyuni-project   File: ConnectionManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ClassMetadata getMetadata(Object target) {
    ClassMetadata retval = null;
    if (target != null) {
        if (target instanceof Class) {
            retval = sessionFactory.getClassMetadata((Class) target);
        }
        else {
            retval = sessionFactory.getClassMetadata(target.getClass());
        }
    }
    return retval;
}
 
Example #14
Source Project: lams   Author: lamsfoundation   File: ActionQueue.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add parent and child entity names so that we know how to rearrange dependencies
 *
 * @param action The action being sorted
 * @param batchIdentifier The batch identifier of the entity affected by the action
 */
private void addParentChildEntityNames(AbstractEntityInsertAction action, BatchIdentifier batchIdentifier) {
	Object[] propertyValues = action.getState();
	ClassMetadata classMetadata = action.getPersister().getClassMetadata();
	if ( classMetadata != null ) {
		Type[] propertyTypes = classMetadata.getPropertyTypes();

		for ( int i = 0; i < propertyValues.length; i++ ) {
			Object value = propertyValues[i];
			Type type = propertyTypes[i];
			addParentChildEntityNameByPropertyAndValue( action, batchIdentifier, type, value );
		}
	}
}
 
Example #15
Source Project: abixen-platform   Author: abixen   File: DatabaseH2Service.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
private void loadSystemTableList(SessionFactory sessionFactory) {
    Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata();
    allClassMetadata.forEach((key, value) -> {
        AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) value;
        SYSTEM_TABLE_LIST.add(abstractEntityPersister.getTableName());
    });
}
 
Example #16
Source Project: bamboobsc   Author: billchen198318   File: DataUtils.java    License: Apache License 2.0 5 votes vote down vote up
public List<String> getEntityNameList(Session session) throws Exception {		
	Map<String, ClassMetadata> classMetadataMap = getClassMetadata(session);
	List<String> names = new ArrayList<String>();
	for (Map.Entry<String, ClassMetadata> entry : classMetadataMap.entrySet()) {
		names.add(entry.getValue().getEntityName());
	}		
	return names;
}
 
Example #17
Source Project: cacheonix-core   Author: cacheonix   File: Printer.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param entity an actual entity object, not a proxy!
 */
public String toString(Object entity, EntityMode entityMode) throws HibernateException {

	// todo : this call will not work for anything other than pojos!
	ClassMetadata cm = factory.getClassMetadata( entity.getClass() );

	if ( cm==null ) return entity.getClass().getName();

	Map result = new HashMap();

	if ( cm.hasIdentifierProperty() ) {
		result.put(
			cm.getIdentifierPropertyName(),
			cm.getIdentifierType().toLoggableString( cm.getIdentifier( entity, entityMode ), factory )
		);
	}

	Type[] types = cm.getPropertyTypes();
	String[] names = cm.getPropertyNames();
	Object[] values = cm.getPropertyValues( entity, entityMode );
	for ( int i=0; i<types.length; i++ ) {
		if ( !names[i].startsWith("_") ) {
			String strValue = values[i]==LazyPropertyInitializer.UNFETCHED_PROPERTY ?
				values[i].toString() :
				types[i].toLoggableString( values[i], factory );
			result.put( names[i], strValue );
		}
	}
	return cm.getEntityName() + result.toString();
}
 
Example #18
Source Project: jeewx   Author: zhangdaiscott   File: GenericBaseCommonDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获得该类的属性和类型
 * 
 * @param entityName
 *            注解的实体类
 */
private <T> void getProperty(Class entityName) {
	ClassMetadata cm = sessionFactory.getClassMetadata(entityName);
	String[] str = cm.getPropertyNames(); // 获得该类所有的属性名称
	for (int i = 0; i < str.length; i++) {
		String property = str[i];
		String type = cm.getPropertyType(property).getName(); // 获得该名称的类型
		org.jeecgframework.core.util.LogUtil.info(property + "---&gt;" + type);
	}
}
 
Example #19
Source Project: spacewalk   Author: spacewalkproject   File: ConnectionManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
public ClassMetadata getMetadata(Object target) {
    ClassMetadata retval = null;
    if (target != null) {
        if (target instanceof Class) {
            retval = sessionFactory.getClassMetadata((Class) target);
        }
        else {
            retval = sessionFactory.getClassMetadata(target.getClass());
        }
    }
    return retval;
}
 
Example #20
Source Project: jadira   Author: JadiraOrg   File: JpaBaseRepository.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines the ID for the entity
 * 
 * @param entity The entity to retrieve the ID for
 * @return The ID
 */
@SuppressWarnings("deprecation") // No good alternative in the Hibernate API yet
protected ID extractId(T entity) {

	final Class<?> entityClass = TypeHelper.getTypeArguments(JpaBaseRepository.class, this.getClass()).get(0);
	final SessionFactory sf = (SessionFactory)(getEntityManager().getEntityManagerFactory());
	final ClassMetadata cmd = sf.getClassMetadata(entityClass);

	final SessionImplementor si = (SessionImplementor)(getEntityManager().getDelegate());

	@SuppressWarnings("unchecked")
	final ID result = (ID) cmd.getIdentifier(entity, si);
	return result;
}
 
Example #21
Source Project: Lottery   Author: caipiao   File: HibernateBaseDao.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 通过Updater更新对象
 * 
 * @param updater
 * @return
 */
@SuppressWarnings("unchecked")
public T updateByUpdater(Updater<T> updater) {
	ClassMetadata cm = sessionFactory.getClassMetadata(getEntityClass());
	T bean = updater.getBean();
	T po = (T) getSession().get(getEntityClass(),
			cm.getIdentifier(bean, POJO));
	updaterCopyToPersistentObject(updater, po, cm);
	return po;
}
 
Example #22
Source Project: jdal   Author: chelu   File: HibernateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** 
 * Initialize Object for use with closed Session. 
 * 
 * @param sessionFactory max depth in recursion
 * @param obj Object to initialize
 * @param initializedObjects list with already initialized Objects
 * @param depth max depth in recursion
 */
private static void initialize(SessionFactory sessionFactory, Object obj, 
		List<Object> initializedObjects, int depth) {
	
	// return on nulls, depth = 0 or already initialized objects
	if (obj == null || depth == 0) { 
		return; 
	}
	
	if (!Hibernate.isInitialized(obj)) {
		// if collection, initialize objects in collection too. Hibernate don't do it.
		if (obj instanceof Collection) {
			initializeCollection(sessionFactory, obj, initializedObjects,
					depth);
			return;
		}
		
		sessionFactory.getCurrentSession().buildLockRequest(LockOptions.NONE).lock(obj);
		Hibernate.initialize(obj);
	}

	// now we can call equals safely. If object are already initializated, return
	if (initializedObjects.contains(obj))
		return;
	
	initializedObjects.add(obj);
	
	// initialize all persistent associaciations.
	ClassMetadata classMetadata = getClassMetadata(sessionFactory, obj);
	
	if (classMetadata == null) {
		return; // Not persistent object
	}
	
	Object[] pvs = classMetadata.getPropertyValues(obj, EntityMode.POJO);
	
	for (Object pv : pvs) {
		initialize(sessionFactory, pv, initializedObjects, depth - 1);
	}
}
 
Example #23
Source Project: jeecg   Author: zhangdaiscott   File: GenericBaseCommonDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获得该类的属性和类型
 *
 * @param entityName
 *            注解的实体类
 */
private <T> void getProperty(Class entityName) {
	ClassMetadata cm = sessionFactory.getClassMetadata(entityName);
	String[] str = cm.getPropertyNames(); // 获得该类所有的属性名称
	for (int i = 0; i < str.length; i++) {
		String property = str[i];
		String type = cm.getPropertyType(property).getName(); // 获得该名称的类型
		org.jeecgframework.core.util.LogUtil.info(property + "---&gt;" + type);
	}
}
 
Example #24
Source Project: judgels   Author: ia-toki   File: LegacySessionFactory.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClassMetadata getClassMetadata(Class entityClass) {
    return null;
}
 
Example #25
Source Project: judgels   Author: ia-toki   File: LegacySessionFactory.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClassMetadata getClassMetadata(String entityName) {
    return null;
}
 
Example #26
Source Project: judgels   Author: ia-toki   File: LegacySessionFactory.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public Map<String, ClassMetadata> getAllClassMetadata() {
    return null;
}
 
Example #27
Source Project: lams   Author: lamsfoundation   File: AbstractEntityPersister.java    License: GNU General Public License v2.0 4 votes vote down vote up
public ClassMetadata getClassMetadata() {
	return this;
}
 
Example #28
Source Project: lams   Author: lamsfoundation   File: SessionFactoryDelegatingImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClassMetadata getClassMetadata(Class entityClass) {
	return delegate.getClassMetadata( entityClass );
}
 
Example #29
Source Project: lams   Author: lamsfoundation   File: SessionFactoryDelegatingImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public ClassMetadata getClassMetadata(String entityName) {
	return delegate.getClassMetadata( entityName );
}
 
Example #30
Source Project: lams   Author: lamsfoundation   File: SessionFactoryDelegatingImpl.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public Map<String, ClassMetadata> getAllClassMetadata() {
	return delegate.getAllClassMetadata();
}