package com.pap.jpa.constant;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.schema.TargetType;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.io.ByteArrayInputStream;
import java.util.*;
/**
* LocalSessionFactoryBean
*
*
*/
public class LocSessFacBeanConstant {
/**
* 存储动态添加的 LocalSessionFactoryBean 信息, 每一个动态模型对应一个 Map。
*/
public static final List<Map<String, SessionFactory>> locSessFacBeanList = new ArrayList<Map<String, SessionFactory>>();
/**
* 获取 SessionFactory
* @param entityManager
* @param dataSource
* @param entityName
* @param XML_MAPPING
* @return
* @throws Exception
*/
public static SessionFactory get(EntityManager entityManager, DataSource dataSource, String entityName, String XML_MAPPING) throws Exception {
SessionFactory sessionFactory = entityManager.getEntityManagerFactory().unwrap(SessionFactory.class);
// ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityName);
// String[] propertyNames = classMetadata.getPropertyNames();
IdentifierGenerator identifierGenerator = ((SessionFactoryImpl) sessionFactory).getIdentifierGenerator(entityName);
if(identifierGenerator != null) {
return sessionFactory;
} else {
for(Map<String, SessionFactory> localSessionFactoryBeanMap : LocSessFacBeanConstant.locSessFacBeanList) {
if(localSessionFactoryBeanMap.containsKey(entityName)) {
return localSessionFactoryBeanMap.get(entityName);
}
}
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource);
localSessionFactoryBean.afterPropertiesSet();
Configuration configuration = localSessionFactoryBean.getConfiguration();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
//读取映射文件
metadataSources.addInputStream(new ByteArrayInputStream(XML_MAPPING.getBytes()));
Metadata metadata = metadataSources.buildMetadata();
//更新数据库Schema,如果不存在就创建表,存在就更新字段,不会影响已有数据
SchemaUpdate schemaUpdate = new SchemaUpdate();
schemaUpdate.execute(EnumSet.of(TargetType.DATABASE), metadata, serviceRegistry);
//合并配置
configuration.addInputStream(new ByteArrayInputStream(XML_MAPPING.getBytes()));
SessionFactory newSessionFactory = configuration.buildSessionFactory(serviceRegistry);
Map<String, SessionFactory> tmp = new HashMap<>();
tmp.put(entityName, newSessionFactory);
locSessFacBeanList.add(tmp);
return newSessionFactory;
}
}
}
评论