pom.xml添加依赖
<!--spring data jpa-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
beans.xml
<?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"
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.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--1 配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="url" value="jdbc:mysql:///spring_data"/>
</bean>
<!--2 配置EntityManagerFactory-->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.ryo"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!--3 配置事务管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--4 配置支持注解的事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--5 配置spring data-->
<jpa:repositories base-package="com.ryo" entity-manager-factory-ref="entityManagerFactory"/>
<context:component-scan base-package="com.ryo"/>
</beans>
测试:如果可以根据一个实体类在数据库中创建一张表,说明配置是没有问题的
package com.ryo;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDataTest {
private ApplicationContext ctx = null;
@Before
public void setup(){
ctx = new ClassPathXmlApplicationContext("file:D:/work/SpringDataProject/src/main/java/resources/beans.xml");
System.out.println("setup");
}
@After
public void tearDown(){
ctx = null;
System.out.println("tearDown");
}
@Test
public void testEntityManagerFactory(){
}
}
手工建立一个类,看能不能在数据库中自动生成
package com.ryo.domain;
//先开发实体类 自动生成数据表
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Employee {
private Integer id;
private String name;
private Integer age;
@GeneratedValue
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(length = 20)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
EmployeeRepository.java
package com.ryo.repository;
import com.ryo.domain.Employee;
import org.springframework.data.repository.Repository;
public interface EmployeeRepository extends Repository<Employee,Integer> {
public Employee findByName(String name);
}
测试:可以根据名字查找到对象(不用写实现类的情况,但是方法名不能乱写,有规则)
package com.ryo;
import com.ryo.domain.Employee;
import com.ryo.repository.EmployeeRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.ArrayList;
import java.util.List;
public class EmployeeRepositoryTest {
private ApplicationContext ctx = null;
private EmployeeRepository employeeRepository = null;
@Before
public void setup() {
ctx = new ClassPathXmlApplicationContext("file:D:/work/SpringDataProject/src/main/java/resources/beans.xml");
employeeRepository = ctx.getBean(EmployeeRepository.class);
System.out.println("setup");
}
@After
public void tearDown() {
ctx = null;
System.out.println("tearDown");
}
@Test
public void testFindByName() {
//org.springframework.data.jpa.repository.support.SimpleJpaRepository@1a9c0566
System.out.println(employeeRepository);
Employee employee = employeeRepository.findByName("zhangsan");
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
Repository Hierarchy
- CrudRepository 继承Repository,实现了CRUD相关的方法
- PagingAndSortingRepository 继承CrudRepository,实现了分页排序相关的方法
- JpaRepository 继承PagingAndSortingRepository,实现JPA相关的方法
- JpaSpecificationExecutor
1)Repository接口是Spring Data 的核心接口,不提供任何方法 空接口,标记接口
public interface Repository<T,ID extends Serializable>{}
2)如果我们定义的接口EmployeeRepository extends Repository
如果我们自己的接口没有extends Repository,运行时会报错:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.imooc.repository.EmployeeRepository' available
3)添加注解能到达到不用extends Repository的功能
@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
写几个例子并测试一下:
在EmployeeRepository中:
// where name like ?% and age <?
public List<Employee> findByNameStartingWithAndAgeLessThan(String name, Integer age);
// where name like %? and age <?
public List<Employee> findByNameEndingWithAndAgeLessThan(String name, Integer age);
// where name in (?,?....) or age <?
public List<Employee> findByNameInOrAgeLessThan(List<String> names, Integer age);
// where name in (?,?....) and age <?
public List<Employee> findByNameInAndAgeLessThan(List<String> names, Integer age);
测试方法:(EmployeeRepositoryTest.java)
@Test
public void testFindByNameStartingWithAndAgeLessThan() {
List<Employee> employees = employeeRepository.findByNameStartingWithAndAgeLessThan("test", 22);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
@Test
public void testFindByNameEndingWithAndAgeLessThan() {
List<Employee> employees = employeeRepository.findByNameEndingWithAndAgeLessThan("6", 23);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
@Test
public void testFindByNameInOrAgeLessThan() {
List<String> names = new ArrayList<String>();
names.add("test1");
names.add("test2");
names.add("test3");
List<Employee> employees = employeeRepository.findByNameInOrAgeLessThan(names, 22);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
@Test
public void testFindByNameInAndAgeLessThan() {
List<String> names = new ArrayList<String>();
names.add("test1");
names.add("test2");
names.add("test3");
List<Employee> employees = employeeRepository.findByNameInAndAgeLessThan(names, 22);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
对于按照方法命名规则来使用的话,有弊端:
1)方法名会比较长: 约定大于配置
2)对于一些复杂的查询,是很难实现
Query注解使用
- 在Repository方法中使用,不需要遵循查询方法命名规则
- 只需要将@Query定义在Repository中的方法之上即可
- 命名参数及索引参数的使用
- 本地查询
@Query("select o from Employee o where id=(select max(id) from Employee t1)")
public Employee getEmployeeByMaxId();
@Query("select o from Employee o where o.name=?1 and o.age=?2")
public List<Employee> queryParams1(String name, Integer age);
@Query("select o from Employee o where o.name=:name and o.age=:age")
public List<Employee> queryParams2(@Param("name")String name, @Param("age")Integer age);
@Query("select o from Employee o where o.name like %?1%")
public List<Employee> queryLike1(String name);
@Query("select o from Employee o where o.name like %:name%")
public List<Employee> queryLike2(@Param("name")String name);
@Query(nativeQuery = true, value = "select count(1) from employee")
public long getCount();
测试:
@Test
public void testGetEmployeeByMaxId() {
Employee employee = employeeRepository.getEmployeeByMaxId();
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
@Test
public void testQueryParams1() {
List<Employee> employees = employeeRepository.queryParams1("zhangsan", 20);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
@Test
public void testQueryParams2() {
List<Employee> employees = employeeRepository.queryParams2("zhangsan", 20);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
@Test
public void testQueryLike1() {
List<Employee> employees = employeeRepository.queryLike1("test");
for (Employee employee : employees) {
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
@Test
public void testQueryLike2() {
List<Employee> employees = employeeRepository.queryLike2("test1");
for (Employee employee : employees) {
System.out.println("id:" + employee.getId()
+ " , name:" + employee.getName()
+ " ,age:" + employee.getAge());
}
}
@Test
public void testGetCount() {
long count = employeeRepository.getCount();
System.out.println("count:" + count);
}
}
更新及删除操作整合事务的使用
- @Modifying注解使用
- @Modifying结合@Query注解执行更新操作
- @Transactional在Spring Data中的使用
@Modifying
@Query("update Employee o set o.age = :age where o.id = :id")
public void update(@Param("id")Integer id, @Param("age")Integer age);
事务:service
package com.imooc.service;
import com.imooc.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Transactional
public void update(Integer id, Integer age) {
employeeRepository.update(id, age);
}
}
测试:
package com.imooc.service;
import com.imooc.repository.EmployeeRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class EmployeeServiceTest {
private ApplicationContext ctx = null;
private EmployeeService employeeService = null;
@Before
public void setup() {
ctx = new ClassPathXmlApplicationContext("beans-new.xml");
employeeService = ctx.getBean(EmployeeService.class);
System.out.println("setup");
}
@After
public void tearDown() {
ctx = null;
System.out.println("tearDown");
}
@Test
public void testUpdate() {
employeeService.update(1, 55);
}
}
事务在Spring data中的使用:
1)事务一般是在Service层
2)@Query、 @Modifying、@Transactional的综合使用