javascript
学习Spring Data JPA
簡介
Spring Data 是spring的一個子項(xiàng)目,在官網(wǎng)上是這樣解釋的:
Spring Data 是為數(shù)據(jù)訪問提供一種熟悉且一致的基于Spring的編程模型,同時仍然保留底層數(shù)據(jù)存儲的特??殊特性。它可以輕松使用數(shù)據(jù)訪問技術(shù),可以訪問關(guān)系和非關(guān)系數(shù)據(jù)庫。
簡而言之就是讓訪問數(shù)據(jù)庫能夠更加便捷。
Spring Data 又包含多個子項(xiàng)目:
Spring Data JPA
Spring Data Mongo DB
Spring Data Redis
Spring Data Solr
本文章主要介紹Spring Data JPA的相關(guān)知識:
傳統(tǒng)方式訪問數(shù)據(jù)庫
使用原始JDBC方式進(jìn)行數(shù)據(jù)庫操作
創(chuàng)建數(shù)據(jù)表:
開發(fā)JDBCUtil工具類
獲取Connection,釋放資源,配置的屬性放在配置文件中,通過代碼的方式將配置文件中的數(shù)據(jù)加載進(jìn)來。
package com.zzh.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();}}} }建立對象模型和DAO
package com.zzh.dao;import com.zzh.domain.Student; import com.zzh.util.JDBCUtil;import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List;/*** Created by zhao on 2017/5/22.*/ public class StudentDAOImpl implements StudentDAO{/*** 查詢學(xué)生*/@Overridepublic 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;}/*** 添加學(xué)生*/@Overridepublic 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);}} }可以看到基于原始的jdbc的編程,同一個dao方法中有太多的重復(fù)代碼。
使用Spring JdbcTemplate進(jìn)行數(shù)據(jù)庫操作
Spring內(nèi)置模板JdbcTemplate的出現(xiàn)大大提高了開發(fā)效率。
- 創(chuàng)建spring配置文件:
- 編寫查詢學(xué)生和保存學(xué)生方法
弊端分析
DAO中有太多的代碼
DAOImpl有大量重復(fù)的代碼
開發(fā)分頁或者其他的功能還要重新封裝
Spring Data
用上面的兩種方式進(jìn)行數(shù)據(jù)庫操作可以感受到代碼的重復(fù)性和易用性都是有缺點(diǎn)的,現(xiàn)在先以一個小例子進(jìn)行spring data操作數(shù)據(jù)庫的基本示范,之后再逐步分析他的具體功能。
小例子
添加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>- 創(chuàng)建一個新的spring配置文件:beans-new.xml:
LocalContainerEntityManagerFactoryBean:
適用于所有環(huán)境的FactoryBean,能全面控制EntityManagerFactory配置,非常適合那種需要細(xì)粒度定制的環(huán)境。
jpaVendorAdapter:
用于設(shè)置JPA實(shí)現(xiàn)廠商的特定屬性,如設(shè)置hibernate的是否自動生成DDL的屬性generateDdl,這些屬性是廠商特定的。目前spring提供HibernateJpaVendorAdapter,OpenJpaVendorAdapter,EclipseJpaVendorAdapter,TopLinkJpaVenderAdapter四個實(shí)現(xiàn)。
jpaProperties:
指定JPA屬性;如Hibernate中指定是否顯示SQL的“hibernate.show_sql”屬性.
- 建立實(shí)體類Employee:
- 自定義接口并繼承Repository接口
繼承的Repository接口泛型里的第一個參數(shù)是要操作的對象,即Employee;第二個參數(shù)是主鍵id的類型,即Integer。
方法即為根據(jù)名字找員工,這個接口是不用寫實(shí)現(xiàn)類的。為什么可以只繼承接口定義了方法就行了呢,因?yàn)閟pring data底層會根據(jù)一些規(guī)則來進(jìn)行相應(yīng)的操作。
所以方法的名字是不能隨便寫的,不然就無法執(zhí)行想要的操作。
- 創(chuàng)建測試類
findByName方法體中先不用寫,直接執(zhí)行空的測試方法,我們的Employee表就自動被創(chuàng)建了,此時表中沒有數(shù)據(jù),向里面添加一條數(shù)據(jù)用于測試:
package com.zzh.repository;import com.zzh.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;@Beforepublic void setUp() throws Exception {ctx = new ClassPathXmlApplicationContext("beans-new.xml");employeeRepository = ctx.getBean(EmployeeRepository.class);}@Afterpublic void tearDown() throws Exception {ctx = null;}@Testpublic void findByName() throws Exception {Employee employee = employeeRepository.findByName("zhangsan");System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());}}再執(zhí)行測試類方法體中的內(nèi)容:
Repository接口
Repository接口是Spring Data的核心接口,不提供任何方法
使用 @ RepositoryDefinition注解跟繼承Repository是同樣的效果,例如 @ RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
Repository接口定義為:public interface Repository<T, ID extends Serializable> {},Repository是一個空接口,標(biāo)記接口;只要將自定義的接口繼承Repository,就會被spring來管理。
Repository的子接口
CrudRepository :繼承 Repository,實(shí)現(xiàn)了CRUD相關(guān)的方法。
PagingAndSortingRepository : 繼承 CrudRepository,實(shí)現(xiàn)了分頁排序相關(guān)的方法。
JpaRepository :繼承 PagingAndSortingRepository ,實(shí)現(xiàn)了JPA規(guī)范相關(guān)的方法。
Repository中查詢方法定義規(guī)則
上面一個例子中使用了findByName作為方法名進(jìn)行指定查詢,但是如果把名字改為其他沒有規(guī)則的比如test就無法獲得正確的查詢結(jié)果。
有如下規(guī)則:
最右邊是sql語法,中間的就是spring data操作規(guī)范,現(xiàn)在寫一些小例子來示范一下:
先在employee表中初始化了一些數(shù)據(jù):
在繼承了Repository接口的EmployeeRepository接口中新增一個方法:
條件是名字以test開頭,并且年齡小于22歲,在測試類中進(jìn)行測試:
得到結(jié)果:
在換一個名字要在某個范圍以內(nèi)并且年齡要小于某個值:
測試類:
得到結(jié)果,只有test1和test2,因?yàn)樵趖est1,test2和test3里面,年齡還要小于22,所以test3被排除了:
弊端分析:
對于按照方法名命名規(guī)則來使用的弊端在于:
方法名會比較長
對于一些復(fù)雜的查詢很難實(shí)現(xiàn)
Query注解
只需要將 @ Query標(biāo)記在繼承了Repository的自定義接口的方法上,就不再需要遵循查詢方法命名規(guī)則。
支持命名參數(shù)及索引參數(shù)的使用
本地查詢
案例使用:
- 查詢Id最大的員工信息:
注意:Query語句中第一個Employee是類名
測試類:
@Testpublic void getEmployeeByMaxId() throws Exception {Employee employee = employeeRepository.getEmployeeByMaxId();System.out.println("id:" + employee.getId() + " name:" + employee.getName() + " age:" + employee.getAge());}- 根據(jù)占位符進(jìn)行查詢
注意占位符后從1開始
@Query("select o from Employee o where o.name=?1 and o.age=?2")List<Employee> queryParams1(String name, Integer age);測試方法:
@Testpublic 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());}}- 根據(jù)命名參數(shù)的方式
- like查詢語句
查詢包含test的記錄:
P.s 這里查詢也得到了結(jié)果,不過我的idea卻在sql語句里面提示有錯,我懷疑是我的idea版本的問題,我的是2017.1.3版本的:
- like語句使用命名參數(shù)
本地查詢
所謂本地查詢,就是使用原生的sql語句進(jìn)行查詢數(shù)據(jù)庫的操作。但是在Query中原生態(tài)查詢默認(rèn)是關(guān)閉的,需要手動設(shè)置為true:
@Query(nativeQuery = true, value = "select count(1) from employee")long getCount();方法是拿到記錄數(shù),這里使用的employee是表而不是類,也是原生態(tài)查詢的特點(diǎn)。
更新操作整合事物使用
- 在dao中定義方法根據(jù)id來更新年齡(Modifying注解代表允許修改)
要注意,執(zhí)行更新或者刪除操作是需要事物支持,所以通過service層來增加事物功能,在update方法上添加Transactional注解。
package com.zzh.service;import com.zzh.repository.EmployeeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;@Service public class EmployeeService {@Autowiredprivate EmployeeRepository employeeRepository;@Transactionalpublic 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); @Transactionalpublic void delete(Integer id) {employeeRepository.delete(id);}CrudRepository接口
- 創(chuàng)建接口繼承CrudRepository
- 在service層中調(diào)用
存入多個對象:
@Transactionalpublic void save(List<Employee> employees) {employeeCrudRepository.save(employees);}創(chuàng)建測試類,將要插入的100條記錄放在List中:
package com.zzh.repository;import com.zzh.domain.Employee; import com.zzh.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 {@Autowiredprivate EmployeeService employeeService;@Testpublic 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);} }為了不影響之前的employee表,現(xiàn)在在Employee類上面加上Table注解,指定一個新的表名,之前沒有加這個注解默認(rèn)使用了類名當(dāng)作表名,也就是employee,現(xiàn)在指定新表test_employee。
執(zhí)行測試類中的方法,控制臺輸出了很多插入語句,打開數(shù)據(jù)庫查看,新表創(chuàng)建成功,同時插入了100條數(shù)據(jù):
CrudRepository總結(jié)
可以發(fā)現(xiàn)在自定義的EmployeeCrudRepository中,只需要聲明接口并繼承CrudRepository就可以直接使用了。
PagingAndSortingRepository接口
該接口包含分頁和排序的功能
帶排序的查詢:findAll(Sort sort)
帶排序的分頁查詢:findAll(Pageable pageable)
自定義接口
package com.zzh.repository;import com.zzh.domain.Employee; import org.springframework.data.repository.PagingAndSortingRepository;public interface EmployeePagingAndSortingRepository extends PagingAndSortingRepository<Employee, Integer> {}測試類
分頁:
package com.zzh.repository;import com.zzh.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 {@Autowiredprivate EmployeePagingAndSortingRepository employeePagingAndSortingRepository;@Testpublic void testPage() {//第0頁,每頁5條記錄Pageable pageable = new PageRequest(0, 5);Page<Employee> page = employeePagingAndSortingRepository.findAll(pageable);System.out.println("查詢的總頁數(shù):"+ page.getTotalPages());System.out.println("總記錄數(shù):"+ page.getTotalElements());System.out.println("當(dāng)前第幾頁:"+ page.getNumber()+1);System.out.println("當(dāng)前頁面對象的集合:"+ page.getContent());System.out.println("當(dāng)前頁面的記錄數(shù):"+ page.getNumberOfElements());}}排序:
在PageRequest的構(gòu)造函數(shù)里還可以傳入一個參數(shù)Sort,而Sort的構(gòu)造函數(shù)可以傳入一個Order,Order可以理解為關(guān)系型數(shù)據(jù)庫中的Order;Order的構(gòu)造函數(shù)Direction和property參數(shù)代表按照哪個字段進(jìn)行升序還是降序。
現(xiàn)在按照id進(jìn)行降序排序:
@Testpublic 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("查詢的總頁數(shù):"+ page.getTotalPages());System.out.println("總記錄數(shù):"+ page.getTotalElements());System.out.println("當(dāng)前第幾頁:" + page.getNumber() + 1);System.out.println("當(dāng)前頁面對象的集合:"+ page.getContent());System.out.println("當(dāng)前頁面的記錄數(shù):"+ page.getNumberOfElements());}可以看到id是從100開始降序排列。
JpaRepository接口
- 創(chuàng)建接口繼承JpaRepository
- 測試類
按id查找員工
package com.zzh.repository;import com.zzh.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 {@Autowiredprivate EmployeeJpaRepository employeeJpaRepository;@Testpublic void testFind() {Employee employee = employeeJpaRepository.findOne(99);System.out.println(employee);} }查看員工是否存在
@Testpublic 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就不能進(jìn)行管理,后面的自定義接口注入就無法完成。
package com.zzh.repository;import com.zzh.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> { }測試類
測試結(jié)果包含分頁,降序排序,查詢條件為年齡大于50
package com.zzh.repository;import com.zzh.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 {@Autowiredprivate EmployeeJpaSpecificationExecutor employeeJpaSpecificationExecutor;/*** 分頁* 排序* 查詢條件: age > 50*/@Testpublic 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:構(gòu)建Predicate*/Specification<Employee> specification = new Specification<Employee>() {@Overridepublic 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("查詢的總頁數(shù):"+ page.getTotalPages());System.out.println("總記錄數(shù):"+ page.getTotalElements());System.out.println("當(dāng)前第幾頁:" + page.getNumber() + 1);System.out.println("當(dāng)前頁面對象的集合:"+ page.getContent());System.out.println("當(dāng)前頁面的記錄數(shù):"+ page.getNumberOfElements());}}可以看到id是從50開始,而不是100,因?yàn)樵O(shè)定了查詢條件age>50
總結(jié)
本篇文章首先介紹以原始的jdbc方式和Spring JdbcTemplate進(jìn)行數(shù)據(jù)庫相關(guān)操作,接著講解了Spring Data Jpa的Repository接口和增刪查改有關(guān)的注解,最后介紹了Repository的一些子接口相關(guān)的crud,分頁和排序。
GitHub地址:SpringDataJpa
轉(zhuǎn)載于:https://www.cnblogs.com/zhaozihan/p/6884077.html
總結(jié)
以上是生活随笔為你收集整理的学习Spring Data JPA的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hdu5299 Circles Game
- 下一篇: JavaScript覆盖率统计实现