Spring笔记(五): spring 整合jdbc、hibernate、jpa

一、简介

(一)需要的jar包

1、需要的jar包:spring、hibernate、mysql、xml、apache-commons等等的jar包。

技术分享  技术分享  技术分享


 技术分享 技术分享


2、以上jar包,如spring、xml和commos都是冗余的。


(二)分析

1、涉及到的实体、service、dao接口、jdbc配置文件以及service实现类都可以通用,只需要实现不同的dao实现类、配置、测试类。

2、通用的源码如下:

1)实体:

<span style="font-size:18px;">@Entity
@Table(name="spring_person")
//@Cache(usage=CacheConcurrencyStrategy.READ_WRITE,region="main.java.com.spring.entity.PersonEntity")
// region用于设置单独的缓存机制,在ehcache.xml 中定义。
public class PersonEntity {
	
	@Id
	@Column(name="person_id",nullable=true )
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int personId;
	
	private String name;
	
	public PersonEntity() {
	}
	
	public int getPersonId() {
		return personId;
	}
	public void setPersonId(int personId) {
		this.personId = personId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
</span>


2)service接口:

<span style="font-size:18px;">/**
 * 业务接口
 * PersonService
 * @title
 * @desc
 * @author SAM-SHO
 * @Jan 17, 2015
 */
public interface PersonService {
	/**
	 * 保存用户实体
	 * @param name
	 */
	public void save(PersonEntity persionEntity);
	
	/**
	 * 删除用户实体
	 * @param id
	 */
	public void delete(int id);
	
	/**
	 * 查询编号为id的使用用户姓名
	 * @param id
	 */
	public String queryPersonName(int id);
	
	/**
	 * 查询编号为id的用户
	 * @param id
	 */
	public PersonEntity getPerson(int id);
	
	/**
	 * 查询所有的PersonEntity
	 * @return
	 */
	public List<PersonEntity> getAllPerson();

	
	/**
	 * 更新实体
	 * @param name
	 * @param id
	 */
	public void update(String name ,int id);
}
</span>

3)service实现类,注入dao的接口。

<span style="font-size:18px;">/**
 * 业务实现类
 * PersionServiceImpl
 * @title
 * @desc
 * @author SAM-SHO
 * @Jan 17, 2015
 */
@Service
@Transactional
public class PersonServiceImpl implements PersonService {

	@Resource
	private PersonDao personDao;//利用接口

	@Transactional(readOnly=true,timeout=100,isolation=Isolation.DEFAULT)
	@Override
	public void save(PersonEntity persionEntity) {
		personDao.save(persionEntity);
	}

	@Transactional(rollbackFor=Exception.class)//任何异常就回滚
	@Override
	public void delete(int id) {
		personDao.delete(id);		
	}

	@Override
	public String queryPersonName(int id) {
		
		return personDao.queryPersonName(id);
	}

	@Transactional(noRollbackFor=RuntimeException.class)//运行异常就不会回滚
	@Override
	public void update(String name, int id) {
		personDao.update(name, id);		
	}
	
	
	public PersonDao getPersonDao() {
		return personDao;
	}

	public void setPersonDao(PersonDao personDao) {
		this.personDao = personDao;
	}

	@Override
	public PersonEntity getPerson(int id) {
		return personDao.getPerson(id);
		 
	}

	@Override
	public List<PersonEntity> getAllPerson() {
		
		return personDao.getAllPerson();
	}
	
}
</span>

4)dao接口

<span style="font-size:18px;">/**
 * 
 * @Title: 
 * @Description:
 * @Copyright: Copyright (c) 2015
 * @Company: 
 *
 * @author: SAM-SHO
 * @version: 1.0
 * @CreateDate:Jan 21, 2015
 */
public interface PersonDao {
	/**
	 * 保存用户实体
	 * @param name
	 */
	public void save(PersonEntity persionEntity);
	
	/**
	 * 删除用户实体
	 * @param id
	 */
	public void delete(int id);
	
	/**
	 * 查询编号为id的使用用户姓名
	 * @param id
	 */
	public String queryPersonName(int id);
	
	/**
	 * 查询编号为id的用户
	 * @param id
	 */
	public PersonEntity getPerson(int id);
	
	/**
	 * 查询所有的PersonEntity
	 * @return
	 */
	public List<PersonEntity> getAllPerson();
	
	/**
	 * 更新实体
	 * @param name
	 * @param id
	 */
	public void update(String name ,int id);
}
</span>

5)jdbc配置文件:

<span style="font-size:18px;">driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/spring?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=root
initialSize=1
maxActive=500
maxIdle=2
minIdle=1
</span>

3、spring中Bean管理与注入,事务都采用注解。


二、spring 整合jdbc

(一)配置文件:

<span style="font-size:18px;"><?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- 自动扫描 -->
	<context:component-scan base-package="main.java.com.spring.jdbc" />
	<!-- 打开aop 注解 -->
	<aop:aspectj-autoproxy />


	<!-- 配置数据源 -->
	<context:property-placeholder location="classpath:jdbc.properties" /><!-- location指向jdbc.properties配置 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${driverClassName}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="${initialSize}" />
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="${maxActive}" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="${maxIdle}" />
		<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="${minIdle}" />
	</bean>

	<!-- 需要把 dataSource 注入到jdbcTemplate-->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<!-- 配置JDBC的事物管理器:DataSourceTransactionManager -->
	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	
	<!-- 注解事物 -->
	<!-- <tx:annotation-driven transaction-manager="txManager" /> -->
	
	<!-- XML事物 -->
	<aop:config>
		<aop:pointcut id="transationPointCut" expression="execution(* main.java.com.spring.jdbc.service..*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="transationPointCut"/>
	</aop:config>
	
	<tx:advice id="txAdvice" transaction-manager="txManager"> 
		<tx:attributes>
			<tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
			<tx:method name="*"  propagation="REQUIRED" isolation="DEFAULT" />
		</tx:attributes>
	</tx:advice>

</beans>

</span>


1、JDBC的事务管理器为:DataSourceTransactionManager



(二)、dao实现类:使用 JdbcTemplate

<span style="font-size:18px;">/**
 * 
 * PersonDaoImpl
 * @title
 * @desc
 * @author SAM-SHO
 * @Dec 28, 2014 
 */

@Repository
public class PersonDaoImpl implements PersonDao {
	
	//使用JdbcTemplate,注意需要在配置中,把dataSource数据源注入到jdbcTemplate
	@Resource
	private JdbcTemplate jdbcTemplate;
	

	@Override
	public void save(PersonEntity persionEntity) {
		String sql = "insert into spring_person (person_id, name) values(?,?)";
		jdbcTemplate.update(sql, new Object[]{persionEntity.getPersonId(),persionEntity.getName()}, new int[]{Types.INTEGER,Types.VARCHAR});
	}

	@Override
	public void delete(int id) {
		String sql = "delete from spring_person  where person_id = ?";
		jdbcTemplate.update(sql, new Object[]{id}, new int[]{Types.INTEGER});
		
	}

	@Override
	public String queryPersonName(int id) {
		
		String sql = "select a.name from spring_person a where a.person_id = ?";
		String name = jdbcTemplate.queryForObject(sql, new Object[]{id}, String.class);
		return name;
	}
	
	public PersonEntity getPerson(int id) {
		
		String sql = "select a.* from spring_person a where a.person_id = ?";
		PersonEntity personEntity = jdbcTemplate.queryForObject(sql, new Object[]{id},new RowMapper<PersonEntity>(){

			@Override
			public PersonEntity mapRow(ResultSet rs, int index) throws SQLException {
				
				PersonEntity person = new PersonEntity();
				person.setPersonId(rs.getInt("person_id"));
				person.setName(rs.getString("name"));
				return person;
			}
		});
		
		return personEntity;
	}
	

	@Override
	public List<PersonEntity> getAllPerson() {
		
		String sql = "select a.* from spring_person a";
		List<PersonEntity> lists = jdbcTemplate.query(sql, new RowMapper<PersonEntity>(){

			@Override
			public PersonEntity mapRow(ResultSet rs, int index) throws SQLException {
				
				PersonEntity person = new PersonEntity();
				person.setPersonId(rs.getInt("person_id"));
				person.setName(rs.getString("name"));
				return person;
			}
		});

		return lists;
	}


	
	
	@Override
	public void update(String name, int id) {
		String sql = "update spring_person a set a.name = ? where a.person_id = ?";
		jdbcTemplate.update(sql, new Object[]{name,id}, new int[]{Types.VARCHAR,Types.INTEGER});
		
	}


}
</span>

1、使用JdbcTemplate,注意需要在配置中,把dataSource数据源注入到jdbcTemplate


(三)、测试

<span style="font-size:18px;">/**
 * SpringJdbcTest
 * @Title: spring整合jdbc测试
 * @Description:
 * @Copyright: Copyright (c) 2015
 * @Company: 
 *
 * @author: SAM-SHO
 * @version: 1.0
 * @CreateDate:Jan 21, 2015
 */
public class SpringJdbcTest {

	private PersonService mPersonService;
	
	@Before
	public void init(){
		ApplicationContext cxt = new ClassPathXmlApplicationContext("application-Jdbc-Context.xml");
		mPersonService = (PersonService) cxt.getBean("personServiceImpl");
		
	}
	
	
	@Test
	public void save() {
		PersonEntity persionEntity = new  PersonEntity();
		persionEntity.setName("Sam-Sho-99");
		//增
		mPersonService.save(persionEntity); 
		
	}
	
	@Test
	public void delete() {
		
		//删除
		mPersonService.delete(5);
		
	}

	@Test
	public void update() {
		
		//修改
		mPersonService.update("蓝胖子", 6);
		
	}
	
	
	@Test
	public void query() {
		
		//查询一个实体
		PersonEntity persionEntity = mPersonService.getPerson(9);
		System.out.println(persionEntity.getPersonId());
		System.out.println(persionEntity.getName());
		
		// 查询名字
		String personName = mPersonService.queryPersonName(8);
		System.out.println(personName);
		
		
		//查询多个实体
		ArrayList<PersonEntity> lists = (ArrayList<PersonEntity>) mPersonService.getAllPerson();
		for (PersonEntity personEntity : lists) {
			System.out.println(personEntity.getPersonId());
			System.out.println(personEntity.getName());
		}
	}
		
}</span>


三、spring 整合hibernate

(一)配置

<span style="font-size:18px;"><?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- 自动扫描 -->
	<context:component-scan base-package="main.java.com.spring.hibernate" />
	<!-- 打开aop 注解 -->
	<aop:aspectj-autoproxy />


	<!-- 配置数据源 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${driverClassName}" />
		<property name="url" value="${url}" />
		<property name="username" value="${username}" />
		<property name="password" value="${password}" />
		<!-- 连接池启动时的初始值 -->
		<property name="initialSize" value="${initialSize}" />
		<!-- 连接池的最大值 -->
		<property name="maxActive" value="${maxActive}" />
		<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
		<property name="maxIdle" value="${maxIdle}" />
		<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
		<property name="minIdle" value="${minIdle}" />
	</bean>

	<!-- Hibernate 的 sessionFactory(使用注解) ,注入数据源和配置 -->
	<!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" hibernate4的配置-->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" destroy-method="destroy">
		<property name="dataSource" ref="dataSource" />

		<!-- 自动扫描entity包下所有实体 -->
		<property name="packagesToScan">
			<list>
				<value>main.java.com.spring.entity</value>
			</list>
		</property>
		
		<property name="hibernateProperties">
			<value>
				hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
				hibernate.hbm2ddl.auto=update
				hibernate.show_sql=false
				hibernate.format_sql=false
				hibernate.cache.use_second_level_cache=true
				hibernate.cache.use_query_cache=false
				hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider 
		      </value>
		</property>

	</bean>

	<!-- 配置Hibernate的事物管理器 :HibernateTransactionManager-->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

	<!-- 注解事物 -->
	<tx:annotation-driven transaction-manager="txManager" /> 

</beans>

</span>

1、启用hibernate的 二级缓存:EhCacheProvider

<span style="font-size:18px;">				hibernate.cache.use_second_level_cache=true
				hibernate.cache.use_query_cache=false
				hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider </span>


2、配置Hibernate的事物管理器 :HibernateTransactionManager 。


(二)dao实现类

<span style="font-size:18px;">/**
 * 
 * PersonDaoImpl
 * @title
 * @desc
 * @author SAM-SHO
 * @Dec 28, 2014 
 */

@Repository
public class PersonDaoImpl implements PersonDao {
	
	
	@Resource
	private SessionFactory sessionFactory;
	
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public void save(PersonEntity persionEntity) {
		getSession().persist(persionEntity);
	}

	@Override
	public void delete(int id) {
		sessionFactory.getCurrentSession().delete(sessionFactory.getCurrentSession().load(PersonEntity.class, id));
		
	}

	@Override
	public String queryPersonName(int id) {
		
		String sql = "select a.name from spring_person a where a.person_id = ?";
		String name = (String) sessionFactory.getCurrentSession().createSQLQuery(sql).setParameter(0, id).uniqueResult();
		return name;
	}
	
	public PersonEntity getPerson(int id) {
		return (PersonEntity) sessionFactory.getCurrentSession().get(PersonEntity.class, id);
		
	}
	

	@SuppressWarnings("unchecked")
	@Override
	public List<PersonEntity> getAllPerson() {
		
		String hql = "from PersonEntity";
		return sessionFactory.getCurrentSession().createQuery(hql).list();//使用hql
		 
	}

	@Override
	public void update(String name, int id) {
		String sql = "update spring_person a set a.name = ? where a.person_id = ?";
		sessionFactory.getCurrentSession().createSQLQuery(sql)//使用sql
		.setParameter(0, name)
		.setParameter(1, id)
		.executeUpdate();
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
</span>

(三)测试

<span style="font-size:18px;">/**
 * 
 * @Title: 
 * @Description:
 * @Copyright: Copyright (c) 2015
 * @Company: 
 *
 * @author: SAM-SHO
 * @version: 1.0
 * @CreateDate:Jan 21, 2015
 */
public class SpringHibernateTest {
	
	
	
	private PersonService mPersonService;
	
	@Before
	public void init(){
		ApplicationContext cxt = new ClassPathXmlApplicationContext("application-hibernate-Context.xml");
		mPersonService = (PersonService) cxt.getBean("personServiceImpl");
		
	}
	
	
	
	@Test
	public void save() {
		PersonEntity persionEntity = new  PersonEntity();
		persionEntity.setName("Sam-Sho-99");
		//增
		mPersonService.save(persionEntity); 
		
	}
	
	@Test
	public void delete() {
		
		//删除
		mPersonService.delete(16);
		
	}

	@Test
	public void update() {
		
		//修改
		mPersonService.update("蓝胖子", 13);
		
	}
	
	
	@Test
	public void query() {
		
		//查询一个实体
//		PersonEntity persionEntity = mPersonService.getPerson(9);
//		System.out.println(persionEntity.getPersonId());
//		System.out.println(persionEntity.getName());
//		
//		// 查询名字
//		String personName = mPersonService.queryPersonName(8);
//		System.out.println(personName);
		
		
		//查询多个实体
		ArrayList<PersonEntity> lists = (ArrayList<PersonEntity>) mPersonService.getAllPerson();
		for (PersonEntity personEntity : lists) {
			System.out.println(personEntity.getPersonId());
			System.out.println(personEntity.getName());
		}
	}
		
}
</span>

(四)使用二级缓存 ehcache.xml

<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<!-- 
    defaultCache节点为缺省的缓存策略
     maxElementsInMemory 内存中最大允许存在的对象数量
     eternal 设置缓存中的对象是否永远不过期 true
     overflowToDisk 把溢出的对象存放到硬盘上
     timeToIdleSeconds 指定缓存对象空闲多长时间就过期,过期的对象会被清除掉
     timeToLiveSeconds 指定缓存对象总的存活时间
     diskPersistent 当jvm结束是是否持久化对象
     diskExpiryThreadIntervalSeconds 指定专门用于清除过期对象的监听线程的轮询时间
 -->
<ehcache>
    <diskStore path="D:\cache"/>
    <defaultCache  maxElementsInMemory="1000" eternal="false" overflowToDisk="true"
        timeToIdleSeconds="120"
        timeToLiveSeconds="180"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="60"/>
	<cache name="main.java.com.spring.entity.PersonEntity" maxElementsInMemory="100" eternal="false"
    overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="600" diskPersistent="false"/>
    <!-- 使用自定义cache,需要在该entity中使用 Cache 的region属性指定-->
</ehcache>
</span>


(五)解决中文和懒加载问题:修改web.xml配置

<span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<welcome-file-list>
	  <welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
 	
    <!-- 加载Spring初始化容器对象的监听器 -->
	<listener>
	    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 设置Spring容器加载配置文件路径 -->
	<context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>classpath*:applicationContext.xml</param-value>
	</context-param>
		
	<!--中文过滤器     START   -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!--中文过滤器			END  -->
	
	<!-- 解决懒加载 -->
	<filter>
		<filter-name>openSessionInView</filter-name>
		<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
		<init-param>
			<param-name>sessionFactoryBeanName</param-name>
			<param-value>sessionFactory</param-value>
		</init-param>
	</filter>	
	<filter-mapping>
		<filter-name>openSessionInView</filter-name>
		<url-pattern>*.action</url-pattern>
	</filter-mapping>
	
	<!-- 设置Struts2  START-->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- Struts2  END-->
  
</web-app>
</span>


四、spring 整合jpa

(一)配置

<span style="font-size:18px;"><?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:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- 自动扫描 -->
	<context:annotation-config/>
	<context:component-scan base-package="main.java.com.spring.jpa" />

  
  	<!-- JPA 当jpa底层使用hibernate实现,那么entityManagerFactory实际上就是sessionFactory-->
  	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
     	 <!-- 持久化单元的名称,value的值必须与persistence.xml文件中 persistence-unit标签中 name属性的值保持一致 -->
      	<property name="persistenceUnitName" value="springJpa"/>
  	</bean>  

	<!-- JPA的事物管理器: JpaTransactionManager-->
  	<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  		<property name="entityManagerFactory" ref="entityManagerFactory"/>
 	 </bean>
 	 
  	<!-- 注解方式的事务 -->
  	<tx:annotation-driven transaction-manager="txManager"/>


</beans>

</span>

(二)Jpa持久化单元配置(代替jdbc.properties)

<span style="font-size:18px;"><?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
   <persistence-unit name="springJpa" transaction-type="RESOURCE_LOCAL"><!-- 本地事务 -->
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
         <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>
         <property name="hibernate.connection.username" value="root"/>
         <property name="hibernate.connection.password" value="root"/>
         <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8"/>
         <property name="hibernate.max_fetch_depth" value="3"/>
         <property name="hibernate.hbm2ddl.auto" value="update"/>
         <property name="hibernate.show_sql" value="false"/>
	     <property name="hibernate.format_sql" value="false"/>
      </properties>
   </persistence-unit>
</persistence>


<!-- 
1. persistence.xml名称不能更改 ,持久化单元名称
2. name="springJpa" 对应   beans.xml中的<property name="persistenceUnitName" value="springJpa"/>

--></span>


1、Jpa的实现使用的还是Hibernate 。

2、持久化单元的配置,一定要放在classpath下 META-INF/ 文件夹下。

技术分享



(三)dao的实现类

<span style="font-size:18px;">/**
 * 
 * @Title: 
 * @Description:
 * @Copyright: Copyright (c) 2015
 * @Company: 
 *
 * @author: SAM-SHO
 * @version: 1.0
 * @CreateDate:Jan 21, 2015
 */
@Repository
public class PersonDaoImpl implements PersonDao {
	
	//注入EntityManager
	@PersistenceContext
	EntityManager entityManager;
	
	@Override
	public void save(PersonEntity persionEntity) {
		
		entityManager.persist(persionEntity);
	}

	@Override
	public void delete(int id) {
		//getReference类似于sessionFactory的load方法
		entityManager.remove(entityManager.getReference(PersonEntity.class, id));
	}

	@Override
	public String queryPersonName(int id) {
		
		String sql = "select a.name from PersonEntity a where a.personId = ?";
		return (String) entityManager.createQuery(sql).setParameter(1, id).getSingleResult();
	}
	
	public PersonEntity getPerson(int id) {
		return entityManager.find(PersonEntity.class, id);
	}
	

	@SuppressWarnings("unchecked")
	@Override
	public List<PersonEntity> getAllPerson() {
		
		String hql = "select o from PersonEntity o";
		return entityManager.createQuery(hql).getResultList();
	}

	@Override
	public void update(String name, int id) {
		String sql = "update PersonEntity a set a.name = ? where a.personId = ?";
		entityManager.createQuery(sql)
		.setParameter(1, name)
		.setParameter(2, id)//这边的参数位置与sessionFaction的不同,从1开始
		.executeUpdate();
		
//		entityManager.merge(PersonEntity)

	}
}
</span>



(四)测试

<span style="font-size:18px;">/**
 * 
 * @Title: 
 * @Description:
 * @Copyright: Copyright (c) 2015
 * @Company: 
 *
 * @author: SAM-SHO
 * @version: 1.0
 * @CreateDate:Jan 21, 2015
 */
public class SpringJpaTest {

	
	private PersonService mPersonService;
	
	@Before
	public void init(){
		ApplicationContext cxt = new ClassPathXmlApplicationContext("application-jpa-Context.xml");
		mPersonService = (PersonService) cxt.getBean("personServiceImpl");
		
	}
	
	@Test
	public void save() {
		PersonEntity persionEntity = new  PersonEntity();
		persionEntity.setName("Sam-Sho-JPA");
		//增
		mPersonService.save(persionEntity); 
		
	}
	
	@Test
	public void delete() {
		
		//删除
		mPersonService.delete(16);
		
	}

	@Test
	public void update() {
		
		//修改
		mPersonService.update("蓝胖子", 16);
		
	}
	
	
	@Test
	public void query() {
		
		//查询一个实体
//		PersonEntity persionEntity = mPersonService.getPerson(16);
//		System.out.println(persionEntity.getPersonId());
//		System.out.println(persionEntity.getName());
//		
//		// 查询名字
		String personName = mPersonService.queryPersonName(16);
		System.out.println(personName);
		
		
		//查询多个实体
//		ArrayList<PersonEntity> lists = (ArrayList<PersonEntity>) mPersonService.getAllPerson();
//		for (PersonEntity personEntity : lists) {
//			System.out.println(personEntity.getPersonId());
//			System.out.println(personEntity.getName());
//		}
	}
	
}
</span>

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。