Spring2.5整合JPA

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: 在网上找了很多Spring整合JPA的文章,试着去写了很多但没有成功,主要原因可能是jar不正确导致的。花了一些时间自已写了一个小例子,Spring2.5整合JPA(Hibernate实现)。 所需要的Spring2.5的jar包如下: 所需要的JPA的jar包如下: Spring2.5整合JPA所需要的jar如下: 文件太大javaeye上传不了,上面的jar下载地址

在网上找了很多Spring整合JPA的文章,试着去写了很多但没有成功,主要原因可能是jar不正确导致的。花了一些时间自已写了一个小例子,Spring2.5整合JPA(Hibernate实现)。

所需要的Spring2.5的jar包如下:

Spring2.5整合JAP所需要的Spring2.5的jar包

所需要的JPA的jar包如下:

Spring2.5整合JAP所需要的JPA的jar包

Spring2.5整合JPA所需要的jar如下:

Spring2.5整合JAP所需要的jar包

文件太大javaeye上传不了,上面的jar下载地址:(http://download.csdn.net/source/1933969

1,配置我们的Spring配置文件beans.xml内空如下:

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4.     xmlns:context="http://www.springframework.org/schema/context" 
  5.     xmlns:aop="http://www.springframework.org/schema/aop" 
  6.     xmlns:tx="http://www.springframework.org/schema/tx" 
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans 
  8.             http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
  9.             http://www.springframework.org/schema/context            
  10.             http://www.springframework.org/schema/context/spring-context-2.5.xsd 
  11.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 
  12.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 
  13.  
  14.     <context:annotation-config  /> 
  15.  
  16.     <bean id="entityManager" 
  17.         class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> 
  18.         <property name="persistenceUnitName" value="mengya"></property> 
  19.     </bean> 
  20.  
  21.     <bean id="JPATranManager" 
  22.         class="org.springframework.orm.jpa.JpaTransactionManager"> 
  23.         <property name="entityManagerFactory" ref="entityManager"></property> 
  24.     </bean> 
  25.  
  26.     <tx:annotation-driven transaction-manager="JPATranManager" /> 
  27.  
  28.     <bean id="studentDAO" 
  29.         class="com.mengya.dao.imple.StudentDAOImple"> 
  30.     </bean> 
  31.  
  32.     <bean id="studentSerivce" 
  33.         class="com.mengya.service.imple.StudentServiceImple"> 
  34.         <property name="studao" ref="studentDAO"></property> 
  35.     </bean> 
  36.  
  37. </beans> 
<?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  />

	<bean id="entityManager"
		class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="mengya"></property>
	</bean>

	<bean id="JPATranManager"
		class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManager"></property>
	</bean>

	<tx:annotation-driven transaction-manager="JPATranManager" />

	<bean id="studentDAO"
		class="com.mengya.dao.imple.StudentDAOImple">
	</bean>

	<bean id="studentSerivce"
		class="com.mengya.service.imple.StudentServiceImple">
		<property name="studao" ref="studentDAO"></property>
	</bean>

</beans>

如查以上xml在你的MyEclipse中出显了一个错误提示,请你自手在你的MyEclipse的XML配置中配置http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

2, 配置JPA的persistence.xml(在src/META-INF/persistence.xml中)内空如下:

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <persistence xmlns="http://java.sun.com/xml/ns/persistence" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" 
  5.     version="1.0"> 
  6.     <persistence-unit name="mengya" transaction-type="RESOURCE_LOCAL"> 
  7.         <properties> 
  8.             <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" /> 
  9.             <property name="hibernate.hbm2ddl.auto" value="update" /> 
  10.             <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver" /> 
  11.             <property name="hibernate.connection.username" value="root" /> 
  12.             <property name="hibernate.connection.password" value="###" /> 
  13.             <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/mp?useUnicode=true&amp;characterEncoding=gbk" /> 
  14.         </properties> 
  15.     </persistence-unit>    
  16. </persistence> 
<?xml version="1.0" encoding="UTF-8"?>
<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="mengya" transaction-type="RESOURCE_LOCAL">
		<properties>
			<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
			<property name="hibernate.hbm2ddl.auto" value="update" />
			<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="###" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/mp?useUnicode=true&amp;characterEncoding=gbk" />
		</properties>
	</persistence-unit>	
</persistence>

3,构建我们的实体Bean如下:

Java代码 复制代码 收藏代码
  1. @Entity 
  2. public class Student { 
  3.  
  4.     private Integer stu_id; 
  5.  
  6.     private String stu_name; 
  7.  
  8.     private String stu_sex; 
  9.  
  10.     private Integer stu_age; 
  11.  
  12.     private String stu_info; 
  13.  
  14.     @Id 
  15.     @GeneratedValue(strategy = GenerationType.AUTO) 
  16.     public Integer getStu_id() { 
  17.         return stu_id; 
  18.     } 
  19.  
  20.     public void setStu_id(Integer stu_id) { 
  21.         this.stu_id = stu_id; 
  22.     } 
  23.  
  24.     @Column(nullable = false
  25.     public String getStu_name() { 
  26.         return stu_name; 
  27.     } 
  28.  
  29.     public void setStu_name(String stu_name) { 
  30.         this.stu_name = stu_name; 
  31.     } 
  32.  
  33.     public Integer getStu_age() { 
  34.         return stu_age; 
  35.     } 
  36.  
  37.     public void setStu_age(Integer stu_age) { 
  38.         this.stu_age = stu_age; 
  39.     } 
  40.  
  41.     public String getStu_info() { 
  42.         return stu_info; 
  43.     } 
  44.  
  45.     public void setStu_info(String stu_info) { 
  46.         this.stu_info = stu_info; 
  47.     } 
  48.  
  49.     public String getStu_sex() { 
  50.         return stu_sex; 
  51.     } 
  52.  
  53.     public void setStu_sex(String stu_sex) { 
  54.         this.stu_sex = stu_sex; 
  55.     } 
  56.  
  57.     @Override 
  58.     public int hashCode() { 
  59.         final int PRIME = 31
  60.         int result = 1
  61.         result = PRIME * result + ((stu_id == null) ? 0 : stu_id.hashCode()); 
  62.         return result; 
  63.     } 
  64.  
  65.     @Override 
  66.     public boolean equals(Object obj) { 
  67.         if (this == obj) 
  68.             return true
  69.         if (obj == null
  70.             return false
  71.         if (getClass() != obj.getClass()) 
  72.             return false
  73.         final Student other = (Student) obj; 
  74.         if (stu_id == null) { 
  75.             if (other.stu_id != null
  76.                 return false
  77.         } else if (!stu_id.equals(other.stu_id)) 
  78.             return false
  79.         return true
  80.     } 
  81.  
@Entity
public class Student {

	private Integer stu_id;

	private String stu_name;

	private String stu_sex;

	private Integer stu_age;

	private String stu_info;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Integer getStu_id() {
		return stu_id;
	}

	public void setStu_id(Integer stu_id) {
		this.stu_id = stu_id;
	}

	@Column(nullable = false)
	public String getStu_name() {
		return stu_name;
	}

	public void setStu_name(String stu_name) {
		this.stu_name = stu_name;
	}

	public Integer getStu_age() {
		return stu_age;
	}

	public void setStu_age(Integer stu_age) {
		this.stu_age = stu_age;
	}

	public String getStu_info() {
		return stu_info;
	}

	public void setStu_info(String stu_info) {
		this.stu_info = stu_info;
	}

	public String getStu_sex() {
		return stu_sex;
	}

	public void setStu_sex(String stu_sex) {
		this.stu_sex = stu_sex;
	}

	@Override
	public int hashCode() {
		final int PRIME = 31;
		int result = 1;
		result = PRIME * result + ((stu_id == null) ? 0 : stu_id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final Student other = (Student) obj;
		if (stu_id == null) {
			if (other.stu_id != null)
				return false;
		} else if (!stu_id.equals(other.stu_id))
			return false;
		return true;
	}

}

4,构建我们的DAO接口及实现:

Java代码 复制代码 收藏代码
  1. public interface StudentDao { 
  2.     public void save(Student stu); 
  3.  
  4.     public void delete(Integer stu_id); 
  5.  
  6.     public void update(Student stu); 
  7.  
  8.     public Student getStudentByPK(Integer stu_id); 
  9.  
  10.     public List<Student> queryAll(); 
public interface StudentDao {
	public void save(Student stu);

	public void delete(Integer stu_id);

	public void update(Student stu);

	public Student getStudentByPK(Integer stu_id);

	public List<Student> queryAll();
}

Java代码 复制代码 收藏代码
  1. public class StudentDAOImple implements StudentDao { 
  2.     @PersistenceContext 
  3.     EntityManager em; 
  4.  
  5.     public void save(Student stu) { 
  6.         em.persist(stu); 
  7.     } 
  8.  
  9.     public void delete(Integer stu_id) { 
  10.         em.remove(em.getReference(Student.class, stu_id)); 
  11.     } 
  12.  
  13.     public void update(Student stu) { 
  14.         em.merge(stu); 
  15.     } 
  16.  
  17.     public Student getStudentByPK(Integer stu_id) { 
  18.         return em.find(Student.class, stu_id); 
  19.     } 
  20.  
  21.     public List<Student> queryAll() { 
  22.         return em.createQuery("select s from Student s").getResultList(); 
  23.     } 
  24.  
public class StudentDAOImple implements StudentDao {
	@PersistenceContext
	EntityManager em;

	public void save(Student stu) {
		em.persist(stu);
	}

	public void delete(Integer stu_id) {
		em.remove(em.getReference(Student.class, stu_id));
	}

	public void update(Student stu) {
		em.merge(stu);
	}

	public Student getStudentByPK(Integer stu_id) {
		return em.find(Student.class, stu_id);
	}

	public List<Student> queryAll() {
		return em.createQuery("select s from Student s").getResultList();
	}

}

5,service的接口及实现:

Java代码 复制代码 收藏代码
  1. @Transactional 
  2. public interface StudentService { 
  3.  
  4.     public void save(Student stu); 
  5.  
  6.     public void delete(Integer stu_id); 
  7.  
  8.     public void update(Student stu); 
  9.  
  10.     @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true
  11.     public Student getStudentByPK(Integer stu_id); 
  12.  
  13.     @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true
  14.     public List<Student> queryAll(); 
  15.  
@Transactional
public interface StudentService {

	public void save(Student stu);

	public void delete(Integer stu_id);

	public void update(Student stu);

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public Student getStudentByPK(Integer stu_id);

	@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
	public List<Student> queryAll();

}

Java代码 复制代码 收藏代码
  1. public class StudentServiceImple implements StudentService { 
  2.      
  3.     private StudentDao studao; 
  4.      
  5.     public void delete(Integer stu_id) { 
  6.         studao.delete(stu_id); 
  7.     } 
  8.  
  9.     public Student getStudentByPK(Integer stu_id) { 
  10.         return studao.getStudentByPK(stu_id); 
  11.     } 
  12.  
  13.     public List<Student> queryAll() { 
  14.         return studao.queryAll(); 
  15.     } 
  16.  
  17.     public void save(Student stu) { 
  18.         studao.save(stu); 
  19.     } 
  20.  
  21.     public void update(Student stu) { 
  22.         studao.update(stu); 
  23.     } 
  24.  
  25.     public void setStudao(StudentDao studao) { 
  26.         this.studao = studao; 
  27.     } 
  28.  
public class StudentServiceImple implements StudentService {
	
	private StudentDao studao;
	
	public void delete(Integer stu_id) {
		studao.delete(stu_id);
	}

	public Student getStudentByPK(Integer stu_id) {
		return studao.getStudentByPK(stu_id);
	}

	public List<Student> queryAll() {
		return studao.queryAll();
	}

	public void save(Student stu) {
		studao.save(stu);
	}

	public void update(Student stu) {
		studao.update(stu);
	}

	public void setStudao(StudentDao studao) {
		this.studao = studao;
	}

}

事务只需@Transactional及可,Spring2.5自动帮我们提供事务,事务配置在我们service中。

6,测试我们的service:

Java代码 复制代码 收藏代码
  1. public class StudentServiceTest extends TestCase { 
  2.  
  3.     public void testSave() { 
  4.         ApplicationContext context = new ClassPathXmlApplicationContext( 
  5.                 "beans.xml"); 
  6.         StudentService stuMght = (StudentService) context 
  7.                 .getBean("studentSerivce"); 
  8.         Student stu = new Student(); 
  9.         stu.setStu_name("xiaobo"); 
  10.         stu.setStu_age(22); 
  11.         stu.setStu_sex("男"); 
  12.         stu.setStu_info("C++"); 
  13.         stuMght.save(stu); 
  14.         System.out.println(stu); 
  15.     } 
  16.  
  17.     public void testDelete() { 
  18.         ApplicationContext context = new ClassPathXmlApplicationContext( 
  19.                 "beans.xml"); 
  20.         StudentService stuMght = (StudentService) context 
  21.                 .getBean("studentSerivce"); 
  22.         stuMght.delete(3); 
  23.     } 
  24.  
  25.     public void testUpdate() { 
  26.         ApplicationContext context = new ClassPathXmlApplicationContext( 
  27.                 "beans.xml"); 
  28.         StudentService stuMght = (StudentService) context 
  29.                 .getBean("studentSerivce"); 
  30.         Student stu = stuMght.getStudentByPK(4); 
  31.         stu.setStu_age(23); 
  32.         stuMght.update(stu); 
  33.     } 
  34.  
  35.     public void testGetStudentByPK() { 
  36.         ApplicationContext context = new ClassPathXmlApplicationContext( 
  37.                 "beans.xml"); 
  38.         StudentService stuMght = (StudentService) context 
  39.                 .getBean("studentSerivce"); 
  40.         Student stu = stuMght.getStudentByPK(5); 
  41.         System.out.println(stu); 
  42.     } 
  43.  
  44.     public void testQueryAll() { 
  45.         ApplicationContext context = new ClassPathXmlApplicationContext( 
  46.                 "beans.xml"); 
  47.         StudentService stuMght = (StudentService) context 
  48.                 .getBean("studentSerivce"); 
  49.         List<Student> stuList = stuMght.queryAll(); 
  50.         for (Student stu : stuList) { 
  51.             System.out.println(stu); 
  52.         } 
  53.     } 
  54.  
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
Java Spring
Springboot+jpa如何设置启动项目表不存在就主动创建,字段没有就新增
Springboot+jpa如何设置启动项目表不存在就主动创建,字段没有就新增
1054 0
Springboot+JPA+Sqlite整合demo
Springboot+JPA+Sqlite整合demo
483 0
|
6月前
|
Java API 数据库
JPA简介:Spring Boot环境下的实践指南
上述内容仅是JPA在Spring Boot环境下使用的冰山一角,实际的实践中你会发现更深更广的应用。总而言之,只要掌握了JPA的规则,你就可以借助Spring Boot无比丰富的功能,娴熟地驾驶这台高性能的跑车,在属于你的程序世界里驰骋。
221 15
|
8月前
|
SQL Java 编译器
深入理解 Spring Data JPA 的导入与使用:以 UserRepository为例
本文深入解析了 Spring Data JPA 中 `UserRepository` 的导入与使用。通过示例代码,详细说明了为何需要导入 `User` 实体类、`JpaRepository` 接口及 `@Repository` 注解。这些导入语句分别用于定义操作实体、提供数据库交互方法和标识数据访问组件。文章还探讨了未导入时的编译问题,并展示了实际应用场景,如用户保存、查询与删除操作。合理使用导入语句,可让代码更简洁高效,充分发挥 Spring Data JPA 的优势。
466 0
|
druid Java 关系型数据库
Spring Boot2 系列教程(二十五)Spring Boot 整合 Jpa 多数据源
Spring Boot2 系列教程(二十五)Spring Boot 整合 Jpa 多数据源
1386 0
|
SQL Java 关系型数据库
Springboot引入jpa来管理数据库
Springboot引入jpa来管理数据库
273 0
Springboot引入jpa来管理数据库
|
Java 数据库连接 API
【Java笔记+踩坑】Spring Data JPA
从常用注解、实体类和各层编写方法入手,详细介绍JPA框架在增删改查等方面的基本用法,以及填充用户名日期、分页查询等高级用法。
【Java笔记+踩坑】Spring Data JPA
|
SQL Java 数据库连接
springBoot+Jpa(hibernate)数据库基本操作
springBoot+Jpa(hibernate)数据库基本操作
334 0
|
安全 Java 数据安全/隐私保护
基于SpringBoot+Spring Security+Jpa的校园图书管理系统
本文介绍了一个基于SpringBoot、Spring Security和JPA开发的校园图书管理系统,包括系统的核心控制器`LoginController`的代码实现,该控制器处理用户登录、注销、密码更新、角色管理等功能,并提供了系统初始化测试数据的方法。
217 0
基于SpringBoot+Spring Security+Jpa的校园图书管理系统