SpringDataJpa
簡介
Spring Data 是爲數據訪問提供一種熟悉且一致的基於Spring的編程模型,同時仍然保留底層數據存儲的特殊特性。它可以輕鬆使用數據訪問技術,可以訪問關係和非關係數據庫。
Spring Data 又包含多個子項目:
- Spring Data JPA
- Spirng Data Mongo DB
- Spring Data Redis
- Spring Data Solr
傳統數據庫訪問數據庫
使用原始JDBC方式進行數據庫操作
創建數據表
jdbc工具類
package com.JDBC.util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtil {
public static Connection getConnection() throws Exception {
InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);
String url = properties.getProperty("jdbc.url");
String user = properties.getProperty("jdbc.user");
String password = properties.getProperty("jdbc.password");
String driverClass = properties.getProperty("jdbc.driverClass");
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
public static void release(ResultSet resultSet, Statement statement,Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
建立POJO
package com.xx;
public class Student {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.xx.dao;
import com.xx.domain.Student;
import com.xx.util.JDBCUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public class StudentDAOImpl implements StudentDAO{
/**
* 查詢學生
*/
@Override
public List<Student> query() {
List<Student> students = new ArrayList<>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String sql = "select * from student";
try {
connection = JDBCUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
Student student = null;
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
student = new Student();
student.setId(id);
student.setAge(age);
student.setName(name);
students.add(student);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.release(resultSet,preparedStatement,connection);
}
return students;
}
/**
* 添加學生
*/
@Override
public void save(Student student) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String sql = "insert into student(name,age) values (?,?)";
try {
connection = JDBCUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, student.getName());
preparedStatement.setInt(2,student.getAge());
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.release(resultSet,preparedStatement,connection);
}
}
}
使用Spring JDBC Template對數據庫進行操作
- 創建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"
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">
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="url" value="${jdbc.url}"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="studentDAO" class="com.zzh.dao.StudentDAOSpringJdbcImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"/>
</bean>
</beans>
- 編寫查詢學生和保存學生的方法
package com.xx.dao;
import com.xx.domain.Student;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StudentDAOSpringJdbcImpl implements StudentDAO{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<Student> query() {
final List<Student> students = new ArrayList<>();
String sql = "select * from student";
jdbcTemplate.query(sql, new RowCallbackHandler() {
@Override
public void processRow(ResultSet resultSet) throws SQLException {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Student student = new Student();
student.setId(id);
student.setAge(age);
student.setName(name);
students.add(student);
}
});
return students;
}
@Override
public void save(Student student) {
String sql = "insert into student(name,age) values (?,?)";
jdbcTemplate.update(sql, new Object[]{student.getName(), student.getAge()});
}
}
弊端分析
DAO中有太多的代碼
DAOImpl有大量重複代碼
開發分頁或者其他功能還要重新封裝
SpringData
例:
- 添加pom依賴
<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>
- 創建一個新的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"
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">
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="url" value="${jdbc.url}"/>
</bean>
<!-- 配置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.zzh"/>
<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>
<!--事務管理器-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!--支持註解的事物-->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--spring data-->
<jpa:repositories base-package="com.zzh" entity-manager-factory-ref="entityManagerFactory"/>
<context:component-scan base-package="com.zzh"/>
</beans>
LocalContainerEntityMangaerFactoryBean:
適用於所有環境的FactoryBean,能全面控制EntityMangaerFactory配置,非常適合那種需要細粒度定製的環境。
jpaVendorAdapter:
用於設置JPA實現廠商的特定屬性,如設置hibernate的是否自動生成DDL的屬性generateDdl,這些屬性是廠商特定的。目前spring提供HibernateJpaVendorAdapter,OpenJpaVendorAdapter,EclipseJpaVendorAdapter,TopLinkJpaVenderAdapter四個實現。
jpaProperties:
指定JPA屬性;如Hibernate中指定是否顯示SQL的“hibernate.show_sql”屬性。
- 建立實體類Employee:
package com.xx;
public class Employee {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
}
- 自定義接口並繼承Repository 接口
繼承的Repository接口泛型裏的第一個參數是要操作的對象,即Employee;第二個參數是主鍵id的類型,即Integer。
方法即爲根據名字找員工,這個接口是不用寫實現類的。爲什麼可以只繼承接口定義了方法就行了呢,因爲spring data底層會根據一些規則來進行相應的操作。
所以方法的名字是不能隨便寫的,不然就無法執行想要的操作。
package com.xx.repository;
import com.zzh.domain.Employee;
import org.springframework.data.repository.Repository;
public interface EmployeeRepository extends Repository<Employee,Integer>{
Employee findByName(String name);
}
- 創建測試類
findByName方法體中先不用寫,直接執行空的測試方法,我們的Employee表就自動被創建了,此時表中沒有數據,向裏面添加一條數據用於測試:
package com.xx.repository;
import com.xx.domain.Employee;
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 EmployeeRepositoryTest {
private ApplicationContext ctx = null;
private EmployeeRepository employeeRepository = null;
@Before
public void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext("beans-new.xml");
employeeRepository = ctx.getBean(EmployeeRepository.class);
}
@After
public void tearDown() throws Exception {
ctx = null;
}
@Test
public void findByName() throws Exception {
Employee employee = employeeRepository.findByName("zhangsan");
System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());
}
}
再執行測試方法中的內容:
Repository接口
- Repository接口是Spring Data的核心接口,不提供任何方法
- 使用 @ RepositoryDefinition註解跟繼承Repository是同樣的效果,例如 @ RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
- Repository接口定義爲:public interface Repository
Repository的子接口
- CrudRepository :繼承 Repository,實現了CRUD相關的方法。
- PagingAndSortingRepository : 繼承 CrudRepository,實現了分頁排序相關的方法。
- JpaRepository :繼承 PagingAndSortingRepository ,實現了JPA規範相關的方法。
Repository中查詢方法定義規則
上面一個例子中使用了findByName作爲方法名進行指定查詢,但是如果把名字改爲其他沒有規則的比如test就無法獲得正確的查詢結果。
有如下規則:
最右邊是sql語法,中間的就是spring data操作規範,現在寫一些小例子來示範一下:
先在employee表中初始化了一些數據:
在繼承了Repository接口的EmployeeRepository接口中新增一個方法:
條件是名字以test開頭,並且年齡小於22歲,在測試類中進行測試:
得到結果:
在換一個名字要在某個範圍以內並且年齡要小於某個值:
測試類:
得到結果,只有test1和test2,因爲在test1,test2和test3裏面,年齡還要小於22,所以test3被排除了:
弊端分析
對於按照方法名命名規則來使用的弊端在於:
- 方法名會比較長
- 對於一些複雜的查詢很難實現
Query註解
- 只需要將 @ Query標記在繼承了Repository的自定義接口的方法上,就不再需要遵循查詢方法命名規則。
- 支持命名參數及索引參數的使用
- 本地查詢
案例
- 查詢Id最大的員工信息
@Query("select o from Employee o where id=(select max(id) from Employee t1)")
Employee getEmployeeById();
注意: Query語句中第一個Employee是類名
測試類:
@Test
public void getEmployeeByMaxId() throws Exception {
Employee employee = employeeRepository.getEmployeeByMaxId();
System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());
}
- 根據佔位符進行查詢
注意: 佔位符從1開始
@Query("select o from Employee o where o.name=?1 and o.age=?2")
List<Employee> queryParams1(String name, Integer age);
測試方法:
@Test
public void queryParams1() throws Exception {
List<Employee> employees = employeeRepository.queryParams1("zhangsan", 20);
for (Employee employee : employees) {
System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());
}
}
- 根據命名參數的方式
@Query("select o from Employee o where o.name=:name and o.age=:age")
List<Employee> queryParams2(@Param("name") String name, @Param("age") Integer age);
- like查詢語句
@Query("select o from Employee o where o.name like %?1%")
List<Employee> queryLike1(String name);
@Test
public void queryLike1() throws Exception {
List<Employee> employees = employeeRepository.queryLike1("test");
for (Employee employee : employees) {
System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());
}
}
- like語句使用命名參數
@Query("select o from Employee o where o.name like %:name%")
List<Employee> queryLike2(@Param("name") String name);
本地查詢
所謂本地查詢,就是使用原生的sql語句進行查詢數據庫的操作。但是在Query中原生態查詢默認是關閉的,需要手動設置爲true:
@Query(nativeQuery = true, value = "select count(1) from employee")
long getCount();
更新操作整合事物使用
- 在DAO中定義方法根據Id來更新年齡(Modifying註解代表允許修改)
@Modifying
@Query("update Employee o set o.age = :age where o.id = :id")
void update(@Param("id") Integer id, @Param("age") Integer age);
要注意,執行更新或者刪除操作是需要事物支持,所以通過service層來增加事物功能,在update方法上添加Transactional註解。
package com.xx.service;
import com.xx.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@Transactional
public void update(Integer id, Integer age) {
employeeRepository.update(id,age);
}
}
刪除操作
刪除操作同樣需要Query註解,Modifying註解和Transactional註解
@Modifying
@Query("delete from Employee o where o.id = :id")
void delete(@Param("id") Integer id);
@Transactional
public void delete(Integer id) {
employeeRepository.delete(id);
}
CrudRepository接口
- 創建接口繼承CrudRepository
package com.xx.repository;
import com.xx.domain.Employee;
import org.springframework.data.repository.CrudRepository;
public interface EmployeeCrudRepository extends CrudRepository<Employee,Integer>{
}
- 在service層中調用
@Autowired
private EmployeeCrudRepository employeeCrudRepository;
- 存入多個對象
@Transactional
public void save(List<Employee> employees) {
employeeCrudRepository.save(employees);
}
- 創建測試類,將要插入的100條記錄放在List中:
package com.xx.repository;
import com.xx.domain.Employee;
import com.xx.service.EmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:beans-new.xml"})
public class EmployeeCrudRepositoryTest {
@Autowired
private EmployeeService employeeService;
@Test
public void testSave() {
List<Employee> employees = new ArrayList<>();
Employee employee = null;
for (int i = 0; i < 100; i++) {
employee = new Employee();
employee.setName("test" + i);
employee.setAge(100 - i);
employees.add(employee);
}
employeeService.save(employees);
}
}
執行後:
CrudRepository總結
可以發現在自定義的EmployeeCrudRepository中,只需要聲明接口並繼承CrudRepository就可以直接使用了。
PagingAndSortingRepository接口
- 該接口包含分頁和排序的功能
- 帶排序的查詢:findAll(Sort sort)
帶排序的分頁查詢:findAll(Pageable pageable)
自定義接口
package com.xx.repository;
import com.xx.domain.Employee;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface EmployeePagingAndSortingRepository extends PagingAndSortingRepository<Employee, Integer> {
}
測試類:
分頁
package com.xx.repository;
import com.xx.domain.Employee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:beans-new.xml"})
public class EmployeePagingAndSortingRepositoryTest {
@Autowired
private EmployeePagingAndSortingRepository employeePagingAndSortingRepository;
@Test
public void testPage() {
//第0頁,每頁5條記錄
Pageable pageable = new PageRequest(0, 5);
Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);
System.out.println("查詢的總頁數:"+ page.getTotalPages());
System.out.println("總記錄數:"+ page.getTotalElements());
System.out.println("當前第幾頁:"+ page.getNumber()+1);
System.out.println("當前頁面對象的集合:"+ page.getContent());
System.out.println("當前頁面的記錄數:"+ page.getNumberOfElements());
}
}
排序:
在PageRequest的構造函數裏還可以傳入一個參數Sort,而Sort的構造函數可以傳入一個Order,Order可以理解爲關係型數據庫中的Order;Order的構造函數Direction和property參數代表按照哪個字段進行升序還是降序。
現在按照id進行降序排序:
@Test
public void testPageAndSort() {
Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
Sort sort = new Sort(order);
Pageable pageable = new PageRequest(0, 5, sort);
Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);
System.out.println("查詢的總頁數:"+ page.getTotalPages());
System.out.println("總記錄數:"+ page.getTotalElements());
System.out.println("當前第幾頁:" + page.getNumber() + 1);
System.out.println("當前頁面對象的集合:"+ page.getContent());
System.out.println("當前頁面的記錄數:"+ page.getNumberOfElements());
}
JpaRepository接口
- 創建接口繼承JpaRepository
package com.xx.repository;
import com.xx.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EmployeeJpaRepository extends JpaRepository<Employee,Integer>{
}
- 測試類:
package com.xx.repository;
import com.xx.domain.Employee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:beans-new.xml"})
public class EmployeeJpaRepositoryTest {
@Autowired
private EmployeeJpaRepository employeeJpaRepository;
@Test
public void testFind() {
Employee employee = employeeJpaRepository.findOne(99);
System.out.println(employee);
}
}
查看員工是否存在
@Test
public void testExists() {
Boolean result1 = employeeJpaRepository.exists(25);
Boolean result2 = employeeJpaRepository.exists(130);
System.out.println("Employee-25: " + result1);
System.out.println("Employee-130: " + result2);
}
JpaSpecificationExecutor接口
- Specification封裝了JPA Criteria查詢條件
沒有繼承其他接口。
自定義接口
這裏要尤爲注意,爲什麼我除了繼承JpaSpecificationExecutor還要繼承JpaRepository,就像前面說的,JpaSpecificationExecutor沒有繼承任何接口,如果我不繼承JpaRepository,那也就意味着不能繼承Repository接口,spring就不能進行管理,後面的自定義接口注入就無法完成。
package com.xx.repository;
import com.xx.domain.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface EmployeeJpaSpecificationExecutor extends JpaSpecificationExecutor<Employee>,JpaRepository<Employee,Integer> {
}
測試類
測試結果包含分頁,降序排序,查詢條件爲年齡大於50
package com.xx.repository;
import com.xx.domain.Employee;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.persistence.criteria.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:beans-new.xml"})
public class EmployeeJpaSpecificationExecutorTest {
@Autowired
private EmployeeJpaSpecificationExecutor employeeJpaSpecificationExecutor;
/**
* 分頁
* 排序
* 查詢條件: age > 50
*/
@Test
public void testQuery() {
Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
Sort sort = new Sort(order);
Pageable pageable = new PageRequest(0, 5, sort);
/**
* root:查詢的類型(Employee)
* query:添加查詢條件
* cb:構建Predicate
*/
Specification<Employee> specification = new Specification<Employee>() {
@Override
public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path path = root.get("age");
return cb.gt(path, 50);
}
};
Page<Employee> page = employeeJpaSpecificationExecutor.findAll(specification, pageable);
System.out.println("查詢的總頁數:"+ page.getTotalPages());
System.out.println("總記錄數:"+ page.getTotalElements());
System.out.println("當前第幾頁:" + page.getNumber() + 1);
System.out.println("當前頁面對象的集合:"+ page.getContent());
System.out.println("當前頁面的記錄數:"+ page.getNumberOfElements());
}
}