hibernate5的一些坑

SessionFactory创建的修改

  如果你是刚刚从hibernate4升级到hibernate5,这时候你的项目肯定就要出错了,什么错呢?

  org.hibernate.MappingException: Unknown entity: xx类

  这是因为SessionFactory创建方式变了

  hibernate4

Configuration conf = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
    applySettings(conf.getProperties()).build();
SessionFactory sessionFactory = conf.buildSessionFactory(serviceRegistry);

  hibernate5

StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder() .applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();

 

hibernate5连接数据库出错

  错误提示

  MySQL server version for the right syntax to use near 'type=InnoDB' at line x

  这个主要是hibernate方言设置出问题了

  修改hibernate.cfg.xml中的dialect,如下

  <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

 

hibernate连接数据库出现乱码或者出现SSL警告

  解决方法如下:

  <property name="connection.url">jdbc:mysql:///maven?characterEncoding=UTF8&amp;userSSL=false</property>

 

maven项目中使用hibernate出错

  出错提示

  org.hibernate.MappingNotFoundException: resource:**.hbm.xml not found

  原因

  原来对于Maven工程,编译的工作是由Maven程序来完成的,而Maven默认只会把src/main/resources文件夹下的文件拷贝到target/classes文件夹下,所以上图中用红框框起来的.hbm.xml都不会被复制到/target/calsses文件夹下,所以Hibernate框架在运行的时候,就会报找不到*.hbm.xml的错误。

  解决办法

  在pom.xml下添加以下代码

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

 

posted @ 2017-05-14 19:58  逆倒尘光  阅读(4570)  评论(0编辑  收藏  举报