Hibernate升级到5.2 - 创建Session Factory并替换PersistentClass以获取实体类属性 [英] Hibernate upgrade to 5.2 - Session Factory creation and replacing PersistentClass for getting entity class properties

查看:1011
本文介绍了Hibernate升级到5.2 - 创建Session Factory并替换PersistentClass以获取实体类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将我的Hibernate版本升级到最新版本5.2.10。我用HibernateUtil代替了SessionFactory创建的代码。


$ b

4.3.11.Final(上一个)

  public class HibernateUtil {
private HibernateUtil(){}
$ b $ private static SessionFactory sessionFactory;

private static配置配置;

public static Configuration getConfiguration(){
return configuration;

private static SessionFactory buildSessionFactory(){
try {
if(sessionFactory == null){
configuration = new Configuration();
configuration.configure(hibernate.cfg.xml);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties())。build();
sessionFactory =配置
.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
catch(Throwable ex){
抛出新的ExceptionInInitializerError(ex);


$ b public static SessionFactory getSessionFactory(){
return buildSessionFactory();


public static Session getSession(){
Session hibernateSession = getSessionFactory()。getCurrentSession();
返回hibernateSession;
}

public static void shutdown(){
getSessionFactory()。close();




$ p $ 5.2 $ Final(New):

  public class HibernateUtil {
private static StandardServiceRegistry registry;
private static SessionFactory sessionFactory;

public static SessionFactory getSessionFactory(){
return buildSessionFactory();


public static SessionFactory buildSessionFactory(){
if(sessionFactory == null){
try {
registry = new StandardServiceRegistryBuilder()。configure ( hibernate.cfg.xml中)建立();
MetadataSources sources = new MetadataSources(registry);
元数据元数据= sources.getMetadataBuilder()。build();
sessionFactory = metadata.getSessionFactoryBuilder()。build();
} catch(Exception e){
e.printStackTrace();
shutdown();
}
}
return sessionFactory;


public static Session getSession(){
Session hibernateSession = getSessionFactory()。getCurrentSession();
返回hibernateSession;


public static void shutdown(){
if(registry!= null){
StandardServiceRegistryBuilder.destroy(registry);
}
}
}

现在我有一种方法,将通过将数据库表名称作为字符串传递给我,以获取列名称列表。我在4.3.11之前就这样做了。最后:

  public static List< String> getColumnNames(String tableName){

List< String> columnList = NULL;

地图< String,ClassMetadata> map = HibernateUtil.getSessionFactory()。getAllClassMetadata();
Iterator< Entry< String,ClassMetadata>> itr = map.entrySet()。iterator();

while(itr.hasNext()){

ClassMetadata classMetaData = itr.next()。getValue();
AbstractEntityPersister aep =(AbstractEntityPersister)classMetaData;

if(aep.getTableName()。split(\\\。)[1] .equalsIgnoreCase(tableName)){

columnList = new ArrayList< String> ;();
String [] propertyNames = classMetaData.getPropertyNames();

for(String property:propertyNames){
try {
PersistentClass persistentClass = HibernateUtil .getConfiguration()。getClassMapping(classMetaData.getEntityName());
String clmName =((Column)persistentClass.getProperty(property).getColumnIterator()。next())。getName();
columnList.add(clmName);
} catch(NoSuchElementException e){
log.error(元素未找到标识为:+属性);
} catch(Exception e){
log.error(e.getMessage());
}
}
break;
}
}

return columnList;
}

现在升级后,它显示getAllClassMetadata方法已过时,获取PersistentClass对象。我看到一个类似的问题这里,但我无法准确找出解决方案。我必须改变我当前代码的哪一部分,才能使getColumnNames()方法与之前完全一样。我引用了文档,它说要使用 EntityManagerFactory.getMetamodel()代替,但是我找不到相同的参考示例。我还需要为此更改SessionFactory创建机制吗?

最后,我对Vlad的文章感谢了。我没有任何改变就采集了集成商代码,并修改了我的 HibernateUtil getColumns()方法。所以这是我的代码:

创建SessionFactory

  public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

public static SessionFactory getSessionFactory(){
return buildSessionFactory();

$ b $ private static SessionFactory buildSessionFactory(){
final BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder()。enableAutoClose()
.applyIntegrator(MetadataExtractorIntegrator.INSTANCE).build() );

final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bootstrapServiceRegistry).configure()。build();
返回新的MetadataSources(serviceRegistry).buildMetadata()。buildSessionFactory();


public static Session getSession(){
Session hibernateSession = getSessionFactory()。getCurrentSession();
返回hibernateSession;
}

public static void shutdown(){
getSessionFactory()。close();


code $元元数据提取器(获取列名称):


  public static List< String> getColumnNames(String tableName){

List< String> columnList = new ArrayList<>(); (Table table:namespace.getTables()){
if(table。

for(Namespace namespace:MetadataExtractorIntegrator.INSTANCE.getDatabase()。getNamespaces()) getName()。equalsIgnoreCase(lookupTableName)){
Iterator< Column> iterator = table.getColumnIterator();
while(iterator.hasNext()){
columnList.add(iterator.next()。getName());
}
break;
}
}
if(!columnList.isEmpty())
break;
}
return columnList;
}


I am currently upgrading my Hibernate version to the latest version 5.2.10. I replaced my code in the HibernateUtil for the SessionFactory creation.

4.3.11.Final (Previous):

 public class HibernateUtil {
   private HibernateUtil() {}

   private static SessionFactory sessionFactory;

    private static Configuration configuration;

    public static Configuration getConfiguration() {
        return configuration;
    }
    private static SessionFactory buildSessionFactory() {
        try {
                     if(sessionFactory == null) {
                        configuration = new Configuration();
                        configuration.configure("hibernate.cfg.xml");
                        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                                .applySettings(configuration.getProperties()).build();
                        sessionFactory = configuration
                                .buildSessionFactory(serviceRegistry);
                     }
            return sessionFactory;
        }
        catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }

    }
    public static SessionFactory getSessionFactory() {
        return buildSessionFactory();
    }

    public static Session getSession() {
        Session hibernateSession = getSessionFactory().getCurrentSession();
        return hibernateSession;
      }

    public static void shutdown() {
       getSessionFactory().close();
    }
}

5.2.10 Final (New):

public class HibernateUtil {
  private static StandardServiceRegistry registry;
  private static SessionFactory sessionFactory;

   public static SessionFactory getSessionFactory() {
        return buildSessionFactory();
   }

  public static SessionFactory buildSessionFactory() {
    if (sessionFactory == null) {
      try {
        registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
        MetadataSources sources = new MetadataSources(registry);
        Metadata metadata = sources.getMetadataBuilder().build();
        sessionFactory = metadata.getSessionFactoryBuilder().build();
      } catch (Exception e) {
        e.printStackTrace();
        shutdown();
      }
    }
    return sessionFactory;
  }

public static Session getSession() {
        Session hibernateSession = getSessionFactory().getCurrentSession();
        return hibernateSession;
      }

  public static void shutdown() {
    if (registry != null) {
      StandardServiceRegistryBuilder.destroy(registry);
    }
  }
}

Now I have a method which would fetch me the list of column names by passing the DB table name as a string. I did it like this before in 4.3.11.Final:

public static List<String> getColumnNames(String tableName) {

        List<String> columnList=null;

        Map<String, ClassMetadata> map = HibernateUtil.getSessionFactory().getAllClassMetadata();
        Iterator<Entry<String, ClassMetadata>>  itr =  map.entrySet().iterator();

        while(itr.hasNext()){

            ClassMetadata classMetaData = itr.next().getValue();
            AbstractEntityPersister aep = (AbstractEntityPersister) classMetaData;

            if(aep.getTableName().split("\\.")[1].equalsIgnoreCase(tableName)){

                columnList = new ArrayList<String>();
                String[] propertyNames = classMetaData.getPropertyNames();

                for(String property : propertyNames){
                        try {
                            PersistentClass persistentClass = HibernateUtil .getConfiguration().getClassMapping(classMetaData.getEntityName());
                            String clmName =  ((Column) persistentClass.getProperty(property).getColumnIterator().next()).getName();
                            columnList.add(clmName);
                        } catch(NoSuchElementException e){
                            log.error("Element not found idenfied as : "+property);
                        } catch(Exception e){
                            log.error(e.getMessage());
                        }
                }
                break;
            }
        }

        return columnList;
    }

Now after the upgrade it shows the method getAllClassMetadata as deprecated and am facing difficulty to get the PersistentClass object. I saw a similar question here but I couldn't exactly figure out the solution. What part of my current code do I have to change for my getColumnNames() method to work exactly like before. I referred the documentation and it says to use the EntityManagerFactory.getMetamodel() instead but i can't find suitable reference examples of the same. Also will I have to change the SessionFactory creation mechanism for this?

解决方案

Well finally I did it thank's to Vlad's article. I took the integrator code without any change and modified my HibernateUtil and the getColumns() method. So here's my code:

SessionFactory creation:

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    public static SessionFactory getSessionFactory() {
        return buildSessionFactory();
    }

    private static SessionFactory buildSessionFactory() {
        final BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder().enableAutoClose()
                .applyIntegrator(MetadataExtractorIntegrator.INSTANCE).build();

        final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bootstrapServiceRegistry).configure().build();
        return new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
    }

    public static Session getSession() {
        Session hibernateSession = getSessionFactory().getCurrentSession();
        return hibernateSession;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}

Metadata Extractor(Get Column names):

public static List<String> getColumnNames(String tableName) {

    List<String> columnList = new ArrayList<>();

    for (Namespace namespace : MetadataExtractorIntegrator.INSTANCE.getDatabase().getNamespaces()) {
        for (Table table : namespace.getTables()) {
            if (table.getName().equalsIgnoreCase(lookupTableName)) {
                Iterator<Column> iterator = table.getColumnIterator();
                while (iterator.hasNext()) {
                    columnList.add(iterator.next().getName());
                }
                break;
            }
        }
        if (!columnList.isEmpty())
            break;
    }
    return columnList;
}

这篇关于Hibernate升级到5.2 - 创建Session Factory并替换PersistentClass以获取实体类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆