hibernate(xml方式)

https://www.tutorialspoint.com/hibernate/hibernate_examples.htm

https://www.journaldev.com/3524/spring-hibernate-integration-example-tutorial

Spring 5.2.2.RELEASE + Hibernate 5.4.18.Final + MySQL 8.0.20

查询数据库

feat: Hibernate查询数据库

我这方式应该是直接耦合了Hibernate,因为是直接使用了sessionFactory,如果用JPA的话应该使用EntityManager。

https://www.javatpoint.com/jpa-vs-hibernate

引入包

其他包见 https://github.com/baicaihenxiao/SpringRoad/blob/ab7486fa4402c074df85e049900e79ff252244ef/pom.xml

  <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>5.2.2.RELEASE</version>
  </dependency>

  <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>5.4.18.Final</version>
  </dependency>

配置sessionFactory bean和transactionManager

sessionFactory bean里面指定hibernate.cfg.xml和*.hbm.xml位置。

hibernate.cfg.xml和*.hbm.xml

hibernate.cfg.xml配置sessionFactory的一些属性

*.hbm.xml将java类和数据表进行映射

使用

Hibernate事务

sessionFactory.getCurrentSession()一定会开启事务

https://stackoverflow.com/questions/29690240/hibernate-sessionfactory-getcurrentsession-without-transactional

sessionFactory一定要绑定事务,否则调用sessionFactory.getCurrentSession()会报错,所以select的句子要设为readonly提高效率。

feat: update insert 和 事务

遇到的问题

hbm.xml not found

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

https://stackoverflow.com/questions/7127608/org-hibernate-mappingnotfoundexception-resource-hbm-xml-not-found

hbm.xml也要放在src/main/resources里,不能放在src/main/java,即使路径写对了,cmd+左键能导航进去也不行。

不能自动创建表

<property name="hibernate.hbm2ddl.auto">create</property>这个不管是create还是update都不能自动创建表,不知道为啥

✅ 已解决

https://stackoverflow.com/questions/1459265/hibernate-create-mysql-innodb-tables-instead-of-myisam

这个里面说用<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>,idea提示这个已经废弃了,用下面这个,update就可以自动生成数据库了。

hibernate版本

用5.2.17.Final版本,会提示一个properties找不到和下面这个,但是没有报错,网上有说不要用5.2版本,我换成了5.4的版本。换成5.2.17.Final又不提示properties找不到了。。。

Last updated

Was this helpful?