Spring与Hibernate整合
Spring与Hibernate整合关键点:
1) Hibernate的SessionFactory对象交给Spring创建;
2) hibernate事务交给spring的声明式事务管理。
SSH整合:
Spring与Struts;
Spring与hibernate整合;
SH整合步骤:
1)引入jar包
连接池/数据库驱动包
Hibernate相关jar
Spring 核心包(5个)
Spring aop 包(4个)
spring-orm-3.2.5.RELEASE.jar 【spring对hibernate的支持】
spring-tx-3.2.5.RELEASE.jar 【事务相关】
2)配置
hibernate.cfg.xml
bean.xml
3)搭建环境、单独测试
package loaderman.dao; import loaderman.entity.Dept; import org.hibernate.SessionFactory; // 数据访问层 public class DeptDao { // Spring与Hibernate整合: IOC容器注入 private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } // 保存一个记录 // Spring与Hibernate整合:事务管理交给Spring public void save(Dept dept) { sessionFactory.getCurrentSession().save(dept); } }
package loaderman.dao; import loaderman.entity.Dept; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.classic.Session; // 数据访问层 public class DeptDao_bak { private static SessionFactory sessionFactory; static { sessionFactory = new Configuration().configure().buildSessionFactory(); } // 保存一个记录 public void save(Dept dept) { // 创建配置管理类对象、创建SessionFactory、创建Session, 执行操作, 关闭 Session session = sessionFactory.openSession(); session.beginTransaction(); // 保存 session.save(dept); session.getTransaction().commit(); session.close(); } }
package loaderman.entity; public class Dept { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="loaderman.entity"> <class name="Dept" table="t_dept"> <id name="id" column="deptId"> <generator class="native"></generator> </id> <property name="name" column="deptName"></property> </class> </hibernate-mapping>
package loaderman.service; import loaderman.dao.DeptDao; import loaderman.entity.Dept; // 业务逻辑层 public class DeptService { private DeptDao deptDao; public void setDeptDao(DeptDao deptDao) { this.deptDao = deptDao; } public void save(Dept dept){ deptDao.save(dept); } }
package loaderman; import loaderman.entity.Dept; import loaderman.service.DeptService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App { // 容器 private ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); @Test public void testApp() throws Exception { DeptService deptServie = (DeptService) ac.getBean("deptService"); System.out.println(deptServie.getClass()); deptServie.save(new Dept()); } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!