下面列出了org.hibernate.type.ManyToOneType#org.hibernate.metadata.ClassMetadata 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
/**
* 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);
}
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;
}
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);
}
});
}
}
/**
* 获取所有数据表
*
* @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;
}
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();
}
}
/**
* 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);
}
/**
* 将更新对象拷贝至实体对象,并处理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);
}
}
}
/**
* 取得对象的主键名,辅助函数.
*
* @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;
}
/**
* 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;
}
@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]");
}
/**
* 获取所有数据表
*
* @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;
}
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;
}
/**
* 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 );
}
}
}
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());
});
}
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;
}
/**
* @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();
}
/**
* 获得该类的属性和类型
*
* @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 + "--->" + type);
}
}
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;
}
/**
* 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;
}
/**
* 通过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;
}
/**
* 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);
}
}
/**
* 获得该类的属性和类型
*
* @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 + "--->" + type);
}
}
@Override
public ClassMetadata getClassMetadata(Class entityClass) {
return null;
}
@Override
public ClassMetadata getClassMetadata(String entityName) {
return null;
}
@Override
public Map<String, ClassMetadata> getAllClassMetadata() {
return null;
}
public ClassMetadata getClassMetadata() {
return this;
}
@Override
public ClassMetadata getClassMetadata(Class entityClass) {
return delegate.getClassMetadata( entityClass );
}
@Override
public ClassMetadata getClassMetadata(String entityName) {
return delegate.getClassMetadata( entityName );
}
@Override
public Map<String, ClassMetadata> getAllClassMetadata() {
return delegate.getAllClassMetadata();
}