Spring Data Jpa使用

Spring Data Jpa简介

Spring Data JPA是Spring Data框架的一个模块。
Spring Data JPA依赖于Spring的核心jar,JPA只有接口和注解,Spring Data JPA的功能实现默是使用的Hibernate,因此还必须引入Hibernate对JPA的支持(整合)项目hibernate-entitymanager。

JPA编程是通过EntityManagerFactory(类似SessionFactory),获得EntityManager (类似Session)进行增删改查,CRUD的方法分别为:
增加 persist()、修改 merge()、删除 remove()、查询 find()

Spring Data JPA配置和基本使用

1.引入spring data jpa和hibernate-entitymanager的依赖;
2.配置DataSource,配置EntityManagerFactory,配置事务,配置JPA扫描。
3.编写接口继承Repository系列接口,按照JPA规范编写相关方法。

具体实例

依赖:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<properties>
<spring.version>4.0.3.RELEASE</spring.version>
<spring.groupId>org.springframework</spring.groupId>
<druid.version>1.0.28</druid.version>
<mysql.version>5.1.45</mysql.version>
<spring.data.jpa.version>1.7.0.RELEASE</spring.data.jpa.version>
<hibernate.entitymanager.version>4.3.6.Final</hibernate.entitymanager.version>
<junit.version>4.12</junit.version>
<aspectjweaver.version>1.8.1</aspectjweaver.version>
</properties>
<dependencies>
<dependency>
<groupId>${spring.groupId}</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>${spring.groupId}</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>${spring.groupId}</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>${spring.groupId}</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>${spring.groupId}</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>${spring.groupId}</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>${spring.data.jpa.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.entitymanager.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectjweaver.version}</version>
</dependency>
</dependencies>

spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.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
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:component-scan base-package="com.tommy.myapp">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:db.properties"/>
<!--alibaba druid数据库连接池配置-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="10"/>
<property name="minIdle" value="10"/>
<property name="maxActive" value="100"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<property name="validationQuery" value="${db.test_sql}"/>
<!-- 指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除.注意: 设置为true后如果要生效,validationQuery参数必须设置为非空字符串 -->
<property name="testWhileIdle" value="true"/>
<!-- 默认值是 true ,当从连接池取连接时,验证这个连接是否有效 -->
<property name="testOnBorrow" value="false"/>
<!-- 默认值是 flase, 当从把该连接放回到连接池的时,验证这个连接是否有效 -->
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat"/>
</bean>
<!-- 实体管理工厂 -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描实体类 -->
<property name="packagesToScan" value="com.tommy.myapp.entity"/>
<!--JPA供应商适配:数据库和方言 -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!-- 数据库类型配置 -->
<property name="database" value="${db.type}"/>
<!-- 是否自动生成DDL建表 -->
<property name="generateDdl" value="true"/>
<!-- 配置dialect方言 -->
<property name="databasePlatform" value="${db.dialect}"/>
<!-- 打印sql -->
<property name="showSql" value="true"/>
</bean>
</property>
<!-- 配置hibernate的其他属性 -->
<property name="jpaProperties">
<props>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 注册驱动 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="append*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="edit*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="repair" propagation="REQUIRED"/>
<tx:method name="get*" propagation="SUPPORTS"/>
<tx:method name="select*" propagation="SUPPORTS"/>
<tx:method name="find*" propagation="SUPPORTS"/>
<tx:method name="load*" propagation="SUPPORTS"/>
<tx:method name="search*" propagation="SUPPORTS"/>
<tx:method name="*" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!-- AOP配置-->
<aop:config proxy-target-class="true">
<aop:pointcut id="myPointcut"
expression="execution(* com.tommy.myapp.service.impl.*.*(..))"/>
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="myPointcut"/>
</aop:config>
<jpa:repositories base-package="com.tommy.myapp.dao" entity-manager-factory-ref="entityManagerFactory"
transaction-manager-ref="transactionManager">
</jpa:repositories>
</beans>

db.properties:

1
2
3
4
5
6
db.type=MYSQL
db.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
db.url=jdbc:mysql://192.168.74.135:3306/test?useUnicode=true&characterEncoding=utf8
db.username=root
db.password=123456
db.test_sql=select 1

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Entity
@Table(name = "t_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private Date birthday;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}

UserDao.java

1
2
3
public interface UserDao extends JpaRepository<User,Long> {
User findByName(String name);
}

单元测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
@TransactionConfiguration(transactionManager = "transactionManager",defaultRollback = true) // 单元测试完毕回滚事务
@Transactional
public class UserDaoTest {
@Autowired
private UserDao userDao;
private Long dbUserId = 0L;
@Test
public void testSave() {
User user = new User();
user.setName("test");
user.setBirthday(new Date());
user = this.userDao.save(user);
assert user.getId() > 0;
dbUserId = user.getId();
}
@Test
public void testFindUserById() {
User user = this.userDao.findOne(dbUserId);
assert user != null;
}
@Test
public void testFindUserByName() {
String name = "test";
User user = this.userDao.findByName(name);
assert user != null;
}
}

相关问题:
1.org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before
解决:在实体类的id字段上加入@GeneratedValue(strategy = GenerationType.AUTO)注解

1
2
3
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

参考:Spring Data JPA框架使用Spring Data JPA简化JPA开发Spring Data系列入门

Donny wechat
欢迎关注我的个人公众号
打赏,是超越赞的一种表达。
Show comments from Gitment