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()
1.引入spring data jpa和hibernate-entitymanager的依赖;
2.配置DataSource,配置EntityManagerFactory,配置事务,配置JPA扫描。
3.编写接口继承Repository系列接口,按照JPA规范编写相关方法。
依赖:
<properties>
<spring.version>4.0.3.RELEASEspring.version>
<spring.groupId>org.springframeworkspring.groupId>
<druid.version>1.0.28druid.version>
<mysql.version>5.1.45mysql.version>
<spring.data.jpa.version>1.7.0.RELEASEspring.data.jpa.version>
<hibernate.entitymanager.version>4.3.6.Finalhibernate.entitymanager.version>
<junit.version>4.12junit.version>
<aspectjweaver.version>1.8.1aspectjweaver.version>
properties>
<dependencies>
<dependency>
<groupId>${spring.groupId}groupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>${spring.groupId}groupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>${spring.groupId}groupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>${spring.groupId}groupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>${spring.groupId}groupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>${spring.groupId}groupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>org.springframework.datagroupId>
<artifactId>spring-data-jpaartifactId>
<version>${spring.data.jpa.version}version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-entitymanagerartifactId>
<version>${hibernate.entitymanager.version}version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${junit.version}version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>${aspectjweaver.version}version>
dependency>
dependencies>
spring.xml
<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"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<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}"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
<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"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="${db.type}"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="${db.dialect}"/>
<property name="showSql" value="true"/>
bean>
property>
<property name="jpaProperties">
<props>
<prop key="hibernate.format_sql">trueprop>
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: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:
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
@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
public interface UserDao extends JpaRepository<User,Long> {
User findByName(String name);
}
单元测试
@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)注解
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
参考:Spring Data JPA框架、使用Spring Data JPA简化JPA开发、Spring Data系列入门