广告
返回顶部
首页 > 资讯 > 数据库 >(9)Spring和Hibernate整合
  • 807
分享到

(9)Spring和Hibernate整合

2024-04-02 19:04:59 807人浏览 安东尼
摘要

spring与Hibernate整合的关键点:1) Hibernate的SessionFactory对象交给Spring创建;2) Hibernate事务交给Spring的声明式事务管理。 Spr


spring与Hibernate整合的关键点:

1) Hibernate的SessionFactory对象交给Spring创建;

2) Hibernate事务交给Spring的声明式事务管理。

 

Spring和Hibernate整合的步骤:

1)引入jar

2)配置:hibernate.cfg.xml、*.hbm.xml、applicationContext.xml

3)搭建环境、单独测试

 

1、引入jar包


hibernate3相关jar包

hibernate3.jar

antlr-2.7.6.jar (required)

commons-collections-3.1.jar (required)

dom4j-1.6.1.jar (required)

javassist-3.12.0.GA.jar (required)

jta-1.1.jar (required)

slf4j-api-1.6.1.jar (required)

hibernate-jpa-2.0-api-1.0.0.Final.jar (jpa)

 

spring-core相关jar包

commons-logging-1.2.jar

spring-beans-3.2.5.RELEASE.jar

spring-context-3.2.5.RELEASE.jar

spring-core-3.2.5.RELEASE.jar

spring-expression-3.2.5.RELEASE.jar

 

spring-aop相关jar包

aopalliance-.jar

aspectjrt.jar

aspectjweaver.jar

spring-aop-3.2.5.RELEASE.jar

 

spring-jdbc相关jar包

spring-jdbc-3.2.5.RELEASE.jar

spring-tx-3.2.5.RELEASE.jar  【事务相关】

 

spring-orm相关jar包

spring-ORM-3.2.5.RELEASE.jar  【spring对hibernate的支持】

 

c3p0相关jar包

c3p0-0.9.1.2.jar

 

mysql相关jar包

Mysql-connector-java-5.1.38-bin.jar

 


2、测试Hibernate


hibernate.cfg.xml 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <!-- 通常,一个session-factory节点代表一个数据库 -->
    <session-factory>
        <!-- 1. 数据库连接配置 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///test</property>	
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.passWord">root</property>
		<!-- 
			数据库方言配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql
		 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        <!-- 2. 其他相关配置 -->
		<!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 2.2 格式化sql -->
		<property name="hibernate.format_sql">false</property>
		<!-- 2.3 自动建表  -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- 配置session的创建方式:线程方式创建session对象 -->
		<property name="hibernate.current_session_context_class">thread</property>

		<!-- 3. 加载所有映射-->
		<mapping resource="com/rk/entity/Dept.hbm.xml"/>		

    </session-factory>
</hibernate-configuration>

Dept.hbm.xml

<?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="com.rk.entity" auto-import="true">
	<class name="Dept" table="T_Department">
		<id name="deptId" column="id">
			<generator class="native"></generator>
		</id>
		<version name="deptVersion" column="dept_version"></version>
		<property name="deptName" column="name"></property>
	</class>
</hibernate-mapping>

Dept.java

package com.rk.entity;

public class Dept
{
	private int deptId;
	private String deptName;
	private int deptVersion;
	public int getDeptId()
	{
		return deptId;
	}
	public void setDeptId(int deptId)
	{
		this.deptId = deptId;
	}
	public String getDeptName()
	{
		return deptName;
	}
	public void setDeptName(String deptName)
	{
		this.deptName = deptName;
	}
	public int getDeptVersion()
	{
		return deptVersion;
	}
	public void setDeptVersion(int deptVersion)
	{
		this.deptVersion = deptVersion;
	}
	@Override
	public String toString()
	{
		return "Dept [deptId=" + deptId + ", deptName=" + deptName + ", deptVersion=" + deptVersion + "]";
	}
	
}

DeptDao.java

package com.rk.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.rk.entity.Dept;

public class DeptDao
{
	private static SessionFactory sf;
	static
	{
		sf = new Configuration().configure().buildSessionFactory();
	}
	
	public Dept findById(int id)
	{
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		
		Dept dept = (Dept) session.get(Dept.class, id);
		
		session.getTransaction().commit();
		return dept;
	}
	
	public void save(Dept dept)
	{
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		
		session.save(dept);
		
		session.getTransaction().commit();
	}
}

DeptService.java

package com.rk.service;

import com.rk.dao.DeptDao;
import com.rk.entity.Dept;

public class DeptService
{
	private DeptDao deptDao = new DeptDao();
	
	public Dept findById(int id)
	{
		return deptDao.findById(id);
	}
	
	public void save(Dept dept)
	{
		deptDao.save(dept);
	}
}

App.java

package com.rk.test;

import org.junit.Test;

import com.rk.entity.Dept;
import com.rk.service.DeptService;

public class App
{
	@Test
	public void test()
	{
		DeptService deptService = new DeptService();
//		Dept dept = deptService.findById(3);
//		System.out.println(dept);
		
		Dept dept = new Dept();
		dept.setDeptName("HelloWorld");
		deptService.save(dept);
	}
}

 



3、测试Spring环境


applicationContext.xml (添加)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
     	http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

	<bean id="dept" class="com.rk.entity.Dept"></bean>

</beans>

App.java (修改)

	@Test
	public void test()
	{
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		Dept dept = (Dept) ac.getBean("dept");
		System.out.println(dept);
	}

 

4、Spring和Hibernate整合




4.1、Hibernate的SessionFactory交给Spring创建


其中,hibernate.cfg.xmlDept.hbm.xmlDept.java三个文件没有发生变化。

DeptDao.java (修改)

package com.rk.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.rk.entity.Dept;

public class DeptDao
{
	private SessionFactory sf;
	public void setSf(SessionFactory sf)
	{
		this.sf = sf;
	}
	
	public Dept findById(int id)
	{
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		
		Dept dept = (Dept) session.get(Dept.class, id);
		
		session.getTransaction().commit();
		return dept;
	}
	
	public void save(Dept dept)
	{
		Session session = sf.getCurrentSession();
		session.beginTransaction();
		
		session.save(dept);
		
		session.getTransaction().commit();
	}
}

DeptService.java (修改)

package com.rk.service;

import com.rk.dao.DeptDao;
import com.rk.entity.Dept;

public class DeptService
{
	private DeptDao deptDao;
	public void setDeptDao(DeptDao deptDao)
	{
		this.deptDao = deptDao;
	}
	
	public Dept findById(int id)
	{
		return deptDao.findById(id);
	}
	
	public void save(Dept dept)
	{
		deptDao.save(dept);
	}
}

applicationContext.xml (修改)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
     	http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
	
	<!-- entity 实例 -->
	<bean id="dept" class="com.rk.entity.Dept" scope="prototype"></bean>
	
	<!-- dao 实例 -->
	<bean id="deptDao" class="com.rk.dao.DeptDao">
		<property name="sf" ref="sessionFactory"></property>
	</bean>
	
	<!-- service 实例 -->
	<bean id="deptService" class="com.rk.service.DeptService">
		<property name="deptDao" ref="deptDao"></property>
	</bean>
	
	<!-- SessionFactory 的实例 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
	</bean>
</beans>

App.java (修改)

package com.rk.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rk.entity.Dept;
import com.rk.service.DeptService;

public class App
{
	@Test
	public void test()
	{
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		DeptService deptService = (DeptService) ac.getBean("deptService");
		
		Dept dept = deptService.findById(3);
		System.out.println(dept);
		
		Dept newDept = (Dept) ac.getBean("dept");
		newDept.setDeptName("HelloWorld");
		deptService.save(newDept);
	}
	
}



 

4.2、Hibernate的事务交给Spring的事务控制


其中,Dept.hbm.xmlDept.java没有发生改变。

DeptDao.java (修改)

package com.rk.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.rk.entity.Dept;

public class DeptDao
{
	private SessionFactory sf;
	public void setSf(SessionFactory sf)
	{
		this.sf = sf;
	}
	
	public Dept findById(int id)
	{
		Session session = sf.getCurrentSession();
		Dept dept = (Dept) session.get(Dept.class, id);
		return dept;
	}
	
	public void save(Dept dept)
	{
		Session session = sf.getCurrentSession();
		session.save(dept);
	}
}

DeptService.java (修改)

在save方法中,加入了int i = 1/0;所以会出错,而save方法处于事务当中,因此两条数据不会保存成功。如果去掉错误,两条数据就可以保存成功了。

package com.rk.service;

import com.rk.dao.DeptDao;
import com.rk.entity.Dept;

public class DeptService
{
	private DeptDao deptDao;
	public void setDeptDao(DeptDao deptDao)
	{
		this.deptDao = deptDao;
	}
	
	public Dept findById(int id)
	{
		return deptDao.findById(id);
	}
	
	public void save(Dept dept)
	{
		deptDao.save(dept);
		
		int i = 1/0;
		
		Dept newDept = new Dept();
		newDept.setDeptName("HAHA_LLO");
		deptDao.save(newDept);
	}
}

hibernate.cfg.xml (修改)

 修改的只有一行:删除或注释下面的配置

<!-- 配置session的创建方式:线程方式创建session对象 -->
<property name="hibernate.current_session_context_class">thread</property>

否则,会报错误:org.hibernate.HibernateException: 方法 is not valid without active transaction。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <!-- 通常,一个session-factory节点代表一个数据库 -->
    <session-factory>
        <!-- 1. 数据库连接配置 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///test</property>	
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
		<!-- 
			数据库方言配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql
		 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        <!-- 2. 其他相关配置 -->
		<!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 2.2 格式化sql -->
		<property name="hibernate.format_sql">false</property>
		<!-- 2.3 自动建表  -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- 配置session的创建方式:线程方式创建session对象 -->
		<!-- <property name="hibernate.current_session_context_class">thread</property> -->

		<!-- 3. 加载所有映射-->
		<mapping resource="com/rk/entity/Dept.hbm.xml"/>		

    </session-factory>
</hibernate-configuration>


applicationContext.xml (修改)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
     	http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
	
	<!-- entity 实例 -->
	<bean id="dept" class="com.rk.entity.Dept" scope="prototype"></bean>
	
	<!-- dao 实例 -->
	<bean id="deptDao" class="com.rk.dao.DeptDao">
		<property name="sf" ref="sessionFactory"></property>
	</bean>
	
	<!-- service 实例 -->
	<bean id="deptService" class="com.rk.service.DeptService">
		<property name="deptDao" ref="deptDao"></property>
	</bean>
	
	<!-- SessionFactory 的实例 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
	</bean>
	
	<!-- 1.事务管理器类 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<constructor-arg name="sessionFactory" ref="sessionFactory"></constructor-arg>
	</bean>
	
	<!-- 2.事务策略配置 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="*" read-only="false"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 3.事务策略应用 -->
	<aop:config>
		<aop:pointcut expression="execution(* com.rk.service.*.*(..))" id="pt"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
	</aop:config>
	
</beans>


App.java (没有变化,进行测试)

package com.rk.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rk.entity.Dept;
import com.rk.service.DeptService;

public class App
{
	@Test
	public void test()
	{
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		DeptService deptService = (DeptService) ac.getBean("deptService");
		
		Dept dept = deptService.findById(3);
		System.out.println(dept);
		
		Dept newDept = (Dept) ac.getBean("dept");
		newDept.setDeptName("HelloWorld");
		deptService.save(newDept);
	}
	
}


4.3、Hibernate的数据源交给Spring创建

这里只涉及到修改hibernate.cfg.xml和applicationContext.xml

hibernate.cfg.xml 中删除以下内容:

        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///test</property>	
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>

applicationContext.xml中添加dataSource和修改sessionFactory

	<!-- 数据源:c3p0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property><!-- 数据库驱动 -->
		<property name="jdbcUrl" value="jdbc:mysql:///test"></property><!-- 数据库连接URL -->
		<property name="user" value="root"></property><!-- 用户名 -->
		<property name="password" value="root"></property><!-- 密码 -->
		<property name="minPoolSize" value="2"></property><!-- Pool最小连接数 -->
		<property name="maxPoolSize" value="10"></property><!-- Pool最大连接数 -->
		<property name="acquireIncrement" value="2"></property><!-- Pool每次增长连接数 -->
		<property name="maxStatements" value="100"></property><!--  -->
	</bean>
	
	<!-- SessionFactory 的实例 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
	</bean>


完整的hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <!-- 通常,一个session-factory节点代表一个数据库 -->
    <session-factory>
        <!-- 1. 数据库连接配置 -->
		<!-- 
			数据库方言配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql
		 -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        <!-- 2. 其他相关配置 -->
		<!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 2.2 格式化sql -->
		<property name="hibernate.format_sql">false</property>
		<!-- 2.3 自动建表  -->
		<property name="hibernate.hbm2ddl.auto">update</property>
		
		<!-- 配置session的创建方式:线程方式创建session对象 -->
		<!-- <property name="hibernate.current_session_context_class">thread</property> -->

		<!-- 3. 加载所有映射-->
		<mapping resource="com/rk/entity/Dept.hbm.xml"/>		

    </session-factory>
</hibernate-configuration>

完整的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
     	http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
	
	<!-- entity 实例 -->
	<bean id="dept" class="com.rk.entity.Dept" scope="prototype"></bean>
	
	<!-- dao 实例 -->
	<bean id="deptDao" class="com.rk.dao.DeptDao">
		<property name="sf" ref="sessionFactory"></property>
	</bean>
	
	<!-- service 实例 -->
	<bean id="deptService" class="com.rk.service.DeptService">
		<property name="deptDao" ref="deptDao"></property>
	</bean>
	
	<!-- 数据源:c3p0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property><!-- 数据库驱动 -->
		<property name="jdbcUrl" value="jdbc:mysql:///test"></property><!-- 数据库连接URL -->
		<property name="user" value="root"></property><!-- 用户名 -->
		<property name="password" value="root"></property><!-- 密码 -->
		<property name="minPoolSize" value="2"></property><!-- Pool最小连接数 -->
		<property name="maxPoolSize" value="10"></property><!-- Pool最大连接数 -->
		<property name="acquireIncrement" value="2"></property><!-- Pool每次增长连接数 -->
		<property name="maxStatements" value="100"></property><!--  -->
	</bean>
	
	<!-- SessionFactory 的实例 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
	</bean>
	
	<!-- 1.事务管理器类 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<constructor-arg name="sessionFactory" ref="sessionFactory"></constructor-arg>
	</bean>
	
	<!-- 2.事务策略配置 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="*" read-only="false"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 3.事务策略应用 -->
	<aop:config>
		<aop:pointcut expression="execution(* com.rk.service.*.*(..))" id="pt"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
	</aop:config>
	
</beans>



4.4、Hibernate的配置全部写到Spring的配置当中

换句话说,就是删除hibernate.cfg.xml,只保留applicationContext.xml文件 

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
     	http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
	
	<!-- entity 实例 -->
	<bean id="dept" class="com.rk.entity.Dept" scope="prototype"></bean>
	
	<!-- dao 实例 -->
	<bean id="deptDao" class="com.rk.dao.DeptDao">
		<property name="sf" ref="sessionFactory"></property>
	</bean>
	
	<!-- service 实例 -->
	<bean id="deptService" class="com.rk.service.DeptService">
		<property name="deptDao" ref="deptDao"></property>
	</bean>
	
	<!-- 数据源:c3p0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property><!-- 数据库驱动 -->
		<property name="jdbcUrl" value="jdbc:mysql:///test"></property><!-- 数据库连接URL -->
		<property name="user" value="root"></property><!-- 用户名 -->
		<property name="password" value="root"></property><!-- 密码 -->
		<property name="minPoolSize" value="2"></property><!-- Pool最小连接数 -->
		<property name="maxPoolSize" value="10"></property><!-- Pool最大连接数 -->
		<property name="acquireIncrement" value="2"></property><!-- Pool每次增长连接数 -->
		<property name="maxStatements" value="100"></property><!--  -->
	</bean>
	
	<!-- 【推荐】方式: 所有的配置全部都在Spring配置文件中完成 -->
	<!-- SessionFactory 的实例 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<!-- 注入连接池对象 -->
		<property name="dataSource" ref="dataSource"></property>

		<!-- hibernate常用配置 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">false</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		
		<!-- hibernate映射配置 :两种写法 -->
<!-- 		
		<property name="mappingLocations">
			<list>
				<value>classpath:com/rk/entity/*.hbm.xml</value>
			</list>
		</property>
 -->		
		<property name="mappingDirectoryLocations">
			<list>
				<value>classpath:com/rk/entity/</value>
			</list>
		</property>
	</bean>
	
	<!-- 1.事务管理器类 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<constructor-arg name="sessionFactory" ref="sessionFactory"></constructor-arg>
	</bean>
	
	<!-- 2.事务策略配置 -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="*" read-only="false"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- 3.事务策略应用 -->
	<aop:config>
		<aop:pointcut expression="execution(* com.rk.service.*.*(..))" id="pt"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
	</aop:config>
	
</beans>


4.5、总结:最终的文件状态


applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
     	http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
	
	<!-- entity 实例 -->
	<bean id="dept" class="com.rk.entity.Dept" scope="prototype"></bean>
	
	<!-- dao 实例 -->
	<bean id="deptDao" class="com.rk.dao.DeptDao">
		<property name="sf" ref="sessionFactory"></property>
	</bean>
	
	<!-- service 实例 -->
	<bean id="deptService" class="com.rk.service.DeptService">
		<property name="deptDao" ref="deptDao"></property>
	</bean>
	
	<!-- 数据源配置:c3p0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver"></property><!-- 数据库驱动 -->
		<property name="jdbcUrl" value="jdbc:mysql:///test"></property><!-- 数据库连接URL -->
		<property name="user" value="root"></property><!-- 用户名 -->
		<property name="password" value="root"></property><!-- 密码 -->
		<property name="minPoolSize" value="2"></property><!-- Pool最小连接数 -->
		<property name="maxPoolSize" value="10"></property><!-- Pool最大连接数 -->
		<property name="acquireIncrement" value="2"></property><!-- Pool每次增长连接数 -->
		<property name="maxStatements" value="100"></property><!--  -->
	</bean>
	
	<!-- ###########Spring与Hibernate整合:SessionFactory  start########### -->
	<!-- 【推荐】方式: 所有的配置全部都在Spring配置文件中完成 -->
	<!-- SessionFactory 的实例 -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<!-- 注入连接池对象 -->
		<property name="dataSource" ref="dataSource"></property>

		<!-- hibernate常用配置 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.format_sql">false</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		
		<!-- hibernate映射配置 :两种写法 -->
<!-- 		
		<property name="mappingLocations">
			<list>
				<value>classpath:com/rk/entity/*.hbm.xml</value>
			</list>
		</property>
 -->		
		<property name="mappingDirectoryLocations">
			<list>
				<value>classpath:com/rk/entity/</value>
			</list>
		</property>
	</bean>	
	<!-- ###########Spring与Hibernate整合:SessionFactory  end########### -->
	
	
	<!-- ###########Spring与Hibernate整合:事务  start########### -->
	<!-- a. 配置事务管理器类 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<constructor-arg name="sessionFactory" ref="sessionFactory"></constructor-arg>
	</bean>
	
	<!-- b. 配置事务增强(拦截到方法后如果管理事务?) -->
	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="*" read-only="false"/>
		</tx:attributes>
	</tx:advice>
	
	<!-- c. Aop配置(应用事务) -->
	<aop:config>
		<aop:pointcut expression="execution(* com.rk.service.*.*(..))" id="pt"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
	</aop:config>
	<!-- ###########Spring与Hibernate整合:事务  end########### -->
</beans>

Dept.hbm.xml

<?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="com.rk.entity" auto-import="true">
	<class name="Dept" table="T_Department">
		<id name="deptId" column="id">
			<generator class="native"></generator>
		</id>
		<version name="deptVersion" column="dept_version"></version>
		<property name="deptName" column="name"></property>
	</class>
</hibernate-mapping>

Dept.java

package com.rk.entity;

public class Dept
{
	private int deptId;
	private String deptName;
	private int deptVersion;
	public int getDeptId()
	{
		return deptId;
	}
	public void setDeptId(int deptId)
	{
		this.deptId = deptId;
	}
	public String getDeptName()
	{
		return deptName;
	}
	public void setDeptName(String deptName)
	{
		this.deptName = deptName;
	}
	public int getDeptVersion()
	{
		return deptVersion;
	}
	public void setDeptVersion(int deptVersion)
	{
		this.deptVersion = deptVersion;
	}
	@Override
	public String toString()
	{
		return "Dept [deptId=" + deptId + ", deptName=" + deptName + ", deptVersion=" + deptVersion + "]";
	}
	
}

DeptDao.java

package com.rk.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.rk.entity.Dept;

public class DeptDao
{
	private SessionFactory sf;
	public void setSf(SessionFactory sf)
	{
		this.sf = sf;
	}
	
	public Dept findById(int id)
	{
		Session session = sf.getCurrentSession();
		Dept dept = (Dept) session.get(Dept.class, id);
		return dept;
	}
	
	public void save(Dept dept)
	{
		Session session = sf.getCurrentSession();
		session.save(dept);
	}
}

DeptService.java

package com.rk.service;

import com.rk.dao.DeptDao;
import com.rk.entity.Dept;

public class DeptService
{
	private DeptDao deptDao;
	public void setDeptDao(DeptDao deptDao)
	{
		this.deptDao = deptDao;
	}
	
	public Dept findById(int id)
	{
		return deptDao.findById(id);
	}
	
	public void save(Dept dept)
	{
		deptDao.save(dept);
		
//		int i = 1/0;
		
		Dept newDept = new Dept();
		newDept.setDeptName("HAHA_LLO");
		deptDao.save(newDept);
	}
}

App.java

package com.rk.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.rk.entity.Dept;
import com.rk.service.DeptService;

public class App
{
	@Test
	public void test()
	{
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		DeptService deptService = (DeptService) ac.getBean("deptService");
		
		Dept dept = deptService.findById(3);
		System.out.println(dept);
		
		Dept newDept = (Dept) ac.getBean("dept");
		newDept.setDeptName("HelloWorld");
		deptService.save(newDept);
	}
	
}

 

 

 

您可能感兴趣的文档:

--结束END--

本文标题: (9)Spring和Hibernate整合

本文链接: https://www.lsjlt.com/news/41553.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • (9)Spring和Hibernate整合
    Spring与Hibernate整合的关键点:1) Hibernate的SessionFactory对象交给Spring创建;2) Hibernate事务交给Spring的声明式事务管理。 Spr...
    99+
    2022-10-18
  • Spring 项目快速整合 Hibernate
    要在Spring项目中快速整合Hibernate,可以按照以下步骤进行操作:1. 添加依赖:在项目的pom.xml文件中添加Hibe...
    99+
    2023-09-14
    Spring
  • Spring整合JPA与Hibernate流程详解
    目录设置Spring的配置文件编写范例的Java类编写Customer实体类编写CustomerDao数据访问接口和类编写CustomerService业务逻辑服务接口和类编写测试类...
    99+
    2023-01-09
    Spring整合JPA Spring整合Hibernate
  • spring整合hibernate的方法是什么
    Spring整合Hibernate的方法有以下几种:1. 使用Spring的HibernateTemplate:Spring提供了H...
    99+
    2023-08-12
    spring hibernate
  • 怎么对struts、spring与hibernate进行整合
    怎么对struts、spring与hibernate进行整合?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。准备三个框架结合的lib包Spring3结合Struts2的步骤如下:...
    99+
    2023-05-31
    struts hibernate spring
  • 基于spring+springmvc+hibernate 整合深入剖析
    目录1.新建一个maven web项目2.pom文件,导入jar包3.配置文件4.spring-mvc和spring整合5.spring和hibernate整合6.总结三大框架反反复...
    99+
    2022-11-12
  • Spring 结合 Hibernate
    applicationContext.xml 文件:<xml version="1.0" encoding="UTF-8"> <beans xmlns="http://www.springframew...
    99+
    2023-01-31
    Spring Hibernate
  • 详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)
    一、整合原理二、导包(41个)1.hibernate(1)hibernate/lib/required  (2)hibernate/lib/jpa | java persist api java的持久化规范(接口)  (3)数据库驱动  2...
    99+
    2023-05-31
    ssh 整合 ava
  • spring结合hibernate示例详解
    单纯Hibernate程序首先是导入hibernate的jar包。 建立用户和用户操作记录实体,Log.Java和User.java。代码如下所示。Log.javaimport java.util.Date; public cla...
    99+
    2023-05-31
    spring hibernate te
  • Spring整合MongoDB
    版本:spring:4.1.3.RELEASEmongo-java-driver.version:3.4.1spring-data-mongodb.version:1.7.0.RELEASE配置:1、pom...
    99+
    2022-10-18
  • Struts+Hibernate+Spring如何组合使用
    这篇文章给大家分享的是有关Struts+Hibernate+Spring如何组合使用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。其实对于S2SH的组合,其实注意几点就可以了:第一: 由于Struts2的Acti...
    99+
    2023-06-17
  • MyEclipse下Spring、Hibernate、Struts如何结合
    这篇文章给大家分享的是有关MyEclipse下Spring、Hibernate、Struts如何结合的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。数据库准备:数据库名称:AT_SMS表名称:admin字段如下:s...
    99+
    2023-06-03
  • Spring boot 整合redis
    ...
    99+
    2021-11-16
    Spring boot 整合redis
  • Spring Boot 整合 Canal
    前言 canal 是阿里巴巴旗下的一款开源项目,纯Java开发。基于数据库增量日志解析,提供增量数据订阅&消费,目前主要支持了MySQL(也支持mariaDB)。 canal [kə’næl],译意...
    99+
    2023-09-02
    java 数据库 mysql
  • 怎么解决Struts Hibernate的整合问题
    这篇文章主要介绍“怎么解决Struts Hibernate的整合问题”,在日常操作中,相信很多人在怎么解决Struts Hibernate的整合问题问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么解决Str...
    99+
    2023-06-17
  • Java之Spring整合Junit
    目录1 测试类中的问题和解决思路1.1 问题1.2 解决思路分析2 配置步骤2.1 第一步:拷贝整合 junit 的必备 jar 包到 lib 目录2.2 第二步:使用@RunWit...
    99+
    2023-05-14
    Java Spring整合Junit Spring整合Junit
  • Spring整合Junit详解
    目录1,整合Junit42,整合Junit51,整合Junit4 maven引入spring-test 和 junit4 <dependency>...
    99+
    2022-11-13
  • Spring和Mybatis整合的原理详解
    目录前言简单猜想案例搭建通过扫描接口正式开始setBeanNamesetApplicationContextafterPropertiespostProcessBeanDefinit...
    99+
    2022-11-13
  • Spring整合Redis完整实例代码
    做过大型软件系统的同学都知道,随着系统数据越来越庞大,越来越复杂,随之带来的问题就是系统性能越来越差,尤其是频繁操作数据库带来的性能损耗更为严重。很多业绩大牛为此提出了众多的解决方案和开发了很多框架以优化这种频繁操作数据库所带来的性能损耗,...
    99+
    2023-05-31
    spring redis edi
  • Spring + Spring Boot + MyBatis + MongoDB的整合教程
    前言我之前是学Spring MVC的,后面听同学说Spring Boot挺好用,极力推荐我学这个鬼。一开始,在网上找Spring Boot的学习资料,他们博文写得不是说不好,而是不太详细。我就在想我要自己写一篇尽可能详细的文章出来,下面话不...
    99+
    2023-05-30
    springboot mybatis mongodb
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作