如果我的博客能够帮到大家能够点个赞,关注一下,以后还会更新更过JavaWeb的高级技术,大家的支持就是我继续更新的动力。谢谢。
今天,来写一遍Spring整合JPA的Demo,Spring框架呢 是我们学习JavaWeb必学的一个框架,非常好用,而且支持对第三方框架的集成,所以在JavaWeb项目中用的比较多。JPA呢是Java Persistence API的简称,中文名:Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。JPA的出现使的我们的ORM映射更加便捷,清晰。废话不多说,开工!!!
一、搭建环境
- 创建Java工程的目录结构(Demo选择Java工程即可)
- 编写Spring的配置文件
<?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:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 配置Spring注解扫描器 -->
<context:component-scan base-package="com.nyist.SpingUnionJPA"></context:component-scan>
<!-- 配置C3p0 数据源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<!-- 配置其他属性 -->
</bean>
<!-- 配置EntityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- 引用 连接池 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 配置Jpa 提供商的适配器,可以通过内部bean的方式来配置 -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"></bean>
</property>
<!-- 配置实体类所在的包 -->
<property name="packagesToScan" value="com.nyist.SpingUnionJPA.Entity"></property>
<!-- 配置JPA的基本属性 例如: JPA 实现产品的属性 -->
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- 配置JPA使用的事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<!-- 配置支持基于注解的事务配置 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
- db.properties
jdbc.username=root
jdbc.password=root
jdbc.jdbcUrl=jdbc:mysql:///jpa
jdbc.driverClass=com.mysql.jdbc.Driver
- 导入Jar包
二、完善工程结构
1.编写实体类
- 在Entity包下创建Person实体类,内容如下:
package com.nyist.SpingUnionJPA.Entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * 至于 这些注解 什么意思 大家可以参考我的上一篇关于JPA的博客 SpingData整合JPA 在这个博客有详细解释 */ @Table(name="jpa_person") @Entity public class Person { @GeneratedValue(strategy=GenerationType.AUTO) @Id @Column(length=10,unique=true,nullable=false) private Integer id; @Column(name="last_name",length=255) private String lastName; @Column(name="email",length=255) private String email; @Column(name="age",length=11,nullable=false) private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Person(Integer id, String lastName, String email, Integer age) { super(); this.id = id; this.lastName = lastName; this.email = email; this.age = age; } public Person() { super(); } @Override public String toString() { return "Person [id=" + id + ", lastName=" + lastName + ", email=" + email + ", age=" + age + "]"; } }
2.创建Dao层
- 创建PersonDao.java 文件,内容如下:
package com.nyist.SpingUnionJPA.Dao; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.stereotype.Repository; import com.nyist.SpingUnionJPA.Entity.Person; //@Repository 将PersonDao 交给Spring容器管理 注入到容器中去 @Repository public class PersonDao { /** * 如何获取和当前事务关联的EntityManager 对象呢? * 通过 @PersistenceContext */ //注入 EntityManagerFactory @PersistenceContext private EntityManager entityManager; public void save(Person person){ entityManager.persist(person); } }
4.编写Service层
- 创建PersonService.java文件,内容如下:
package com.nyist.SpingUnionJPA.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.nyist.SpingUnionJPA.Dao.PersonDao; import com.nyist.SpingUnionJPA.Entity.Person; @Service public class PersonService { @Autowired private PersonDao personDao; @Transactional public void savePerson(Person person1,Person person2){ personDao.save(person1); personDao.save(person2); } }
5.测试
- 测试类如下:
package com.nyist.SpingUnionJPA.Test; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.nyist.SpingUnionJPA.Entity.Person; import com.nyist.SpingUnionJPA.Service.PersonService; public class TestJPA { private PersonService personService = null; private ApplicationContext ctx = null; @Before public void before(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); personService = ctx.getBean(PersonService.class); } @Test public void testJPA(){ ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ComboPooledDataSource dataSource = (ComboPooledDataSource)ctx.getBean("dataSource"); System.out.println(dataSource); } @Test public void testPersonService(){ Person person1 = new Person(); person1.setAge(12); person1.setEmail("qq@qq.com"); person1.setLastName("NiHao"); Person person2 = new Person(); person2.setAge(13); person2.setEmail("QQ@qq.com"); person2.setLastName("Hello World "); personService.savePerson(person1, person2); } }
6.结果
7.项目结构
8.源码下载:下载