Spring Data JPA:Spring Data JPA 是 spring data 項目下的一個模塊。提供了一套基於 JPA標準操作數據庫的簡化方案。底層默認的是依賴 Hibernate JPA 來實現的。
Spring Data JPA 的技術特點:我們只需要定義接口並集成 Spring Data JPA 中所提供的接口就可以了。不需要編寫接口實現類。
一、 創建 Spring
1 導入 jar 包
2 修改配置文件
<!-- Spring Data JPA 的配置 -->
<!-- base-package:掃描dao接口所在的包 -->
<jpa:repositories base-package="com.bjsxt.dao"/>
<?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:aop="http://www.springframework.org/schema/aop" 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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置讀取properties文件的工具類 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置c3p0數據庫連接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver.class}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- Spring整合JPA 配置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">
<!-- hibernate相關的屬性的注入 -->
<!-- 配置數據庫類型 -->
<property name="database" value="MYSQL"/>
<!-- 正向工程 自動創建表 -->
<property name="generateDdl" value="true"/>
<!-- 顯示執行的SQL -->
<property name="showSql" value="true"/>
</bean>
</property>
<!-- 掃描實體的包 -->
<property name="packagesToScan">
<list>
<value>com.bjsxt.pojo</value>
</list>
</property>
</bean>
<!-- 配置Hibernate的事務管理器 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 配置開啓註解事務處理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 配置springIOC的註解掃描 -->
<context:component-scan base-package="com.bjsxt"/>
<!-- Spring Data JPA 的配置 -->
<!-- base-package:掃描dao接口所在的包 -->
<jpa:repositories base-package="com.bjsxt.dao"/>
</beans>
3 編寫 Dao
public interface UsersDao extends JpaRepository<Users, Integer> {
}
4 編寫測試代碼
package com.bjsxt.test;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.bjsxt.dao.UsersDao;
import com.bjsxt.pojo.Users;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class UsersDaoImplTest {
@Autowired
private UsersDao usersDao;
/**
* 添加用戶
*/
@Test
@Transactional// 在測試類對於事務提交方式默認的是回滾。
@Rollback(false)//取消自動回滾
public void testInsertUsers(){
Users users = new Users();
users.setUserage(24);
users.setUsername("張三");
this.usersDao.save(users);
}
}
二、 Spring Data JPA 的接口繼承結構
三、 Spring Data JPA 的運行原理
@PersistenceContext(name="entityManagerFactory")
private EntityManager em;
@Test
public void test1(){
//org.springframework.data.jpa.repository.support.SimpleJpaRepository@fba8bf
//System.out.println(this.usersDao);
//class com.sun.proxy.$Proxy29 代理對象 是基於 JDK 的動態代理方式創建的
//System.out.println(this.usersDao.getClass());
JpaRepositoryFactory factory = new JpaRepositoryFactory(em);
//getRepository(UsersDao.class);可以幫助我們爲接口生成實現類。而這個實現類是 SimpleJpaRepository 的對象
//要求:該接口必須要是繼承 Repository 接口
UsersDao ud = factory.getRepository(UsersDao.class);
System.out.println(ud);
System.out.println(ud.getClass());
}
四、 Repository 接口
Repository 接口是 Spring Data JPA 中爲我我們提供的所有接口中的頂層接口
Repository 提供了兩種查詢方式的支持
1)基於方法名稱命名規則查詢
2)基於@Query 註解查詢
1.1創建接口
package com.bjsxt.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.Repository;
import com.bjsxt.pojo.Users;
/**
* Repository接口講解
* @author Administrator
*
*/
public interface UsersDao extends Repository<Users, Integer> {
List<Users> findByUsernameIs(String string);
List<Users> findByUsernameLike(String string);
List<Users> findByUsernameAndUserageGreaterThanEqual(String name,Integer age);
}
1.2測試類
package com.bjsxt.test;
import java.util.List;
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 com.bjsxt.dao.UsersDao;
import com.bjsxt.pojo.Users;
/**
* Repository接口測試
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 需求:使用用戶名作爲查詢條件
*/
@Test
public void test1(){
/**
* 判斷相等的條件,有三種表示方式
* 1,什麼都不寫,默認的就是做相等判斷
* 2,Is
* 3,Equal
*/
List<Users> list = this.usersDao.findByUsernameIs("王五");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 需求:根據用戶姓名做Like處理
* Like:條件關鍵字
*/
@Test
public void test2(){
List<Users> list = this.usersDao.findByUsernameLike("王%");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 需求:查詢名稱爲王五,並且他的年齡大於等於22歲
*/
@Test
public void test3(){
List<Users> list = this.usersDao.findByUsernameAndUserageGreaterThanEqual("王五", 22);
for (Users users : list) {
System.out.println(users);
}
}
}
2 基於@Query 註解的查詢
2.1通過 JPQL 語句查詢
JPQL:通過 Hibernate 的 HQL 演變過來的。他和 HQL 語法及其相似。
2.1.1創建接口
package com.bjsxt.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import com.bjsxt.pojo.Users;
/**
* Repository接口講解
* @author Administrator
*
*/
public interface UsersDao extends Repository<Users, Integer> {
//方法名稱命名規則
List<Users> findByUsernameIs(String string);
List<Users> findByUsernameLike(String string);
List<Users> findByUsernameAndUserageGreaterThanEqual(String name,Integer age);
//使用@Query註解查詢
@Query(value="from Users where username = ?")
List<Users> queryUserByNameUseJPQL(String name);
@Query("from Users where username like ?")
List<Users> queryUserByLikeNameUseJPQL(String name);
@Query("from Users where username = ? and userage >= ?")
List<Users> queryUserByNameAndAge(String name,Integer age);
}
2.1.2測試類
package com.bjsxt.test;
import java.util.List;
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 com.bjsxt.dao.UsersDao;
import com.bjsxt.pojo.Users;
/**
* Repository接口測試
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 測試@Query查詢 JPQL
*/
@Test
public void test4(){
List<Users> list = this.usersDao.queryUserByNameUseJPQL("王五");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 測試@Query查詢 JPQL
*/
@Test
public void test5(){
List<Users> list = this.usersDao.queryUserByLikeNameUseJPQL("王%");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 測試@Query查詢 JPQL
*/
@Test
public void test6(){
List<Users> list = this.usersDao.queryUserByNameAndAge("王五", 22);
for (Users users : list) {
System.out.println(users);
}
}
}
2.2通過 SQL 語句查詢
2.2.1創建接口
nativeQuery:默認的是 false.表示不開啓 sql 查詢。是否對 value 中的語句做轉義。
nativeQuery=true
//使用@Query註解查詢SQL
//nativeQuery:默認的是false.表示不開啓sql查詢。是否對value中的語句做轉義。
@Query(value="select * from t_users where username = ?",nativeQuery=true)
List<Users> queryUserByNameUseSQL(String name);
@Query(value="select * from t_users where username like ?",nativeQuery=true)
List<Users> queryUserByLikeNameUseSQL(String name);
@Query(value="select * from t_users where username = ? and userage >= ?",nativeQuery=true)
List<Users> queryUserByNameAndAgeUseSQL(String name,Integer age);
2.2.2測試類
/**
* 測試@Query查詢 SQL
*/
@Test
public void test7(){
List<Users> list = this.usersDao.queryUserByNameUseSQL("王五");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 測試@Query查詢 SQL
*/
@Test
public void test8(){
List<Users> list = this.usersDao.queryUserByLikeNameUseSQL("王%");
for (Users users : list) {
System.out.println(users);
}
}
/**
* 測試@Query查詢 SQL
*/
@Test
public void test9(){
List<Users> list = this.usersDao.queryUserByNameAndAgeUseSQL("王五", 22);
for (Users users : list) {
System.out.println(users);
}
}
3 通過@Query 註解完成數據更新
3.1創建接口
@Query("update Users set userage = ? where userid = ?")
@Modifying //@Modifying 當前語句是一個更新語句
void updateUserAgeById(Integer age,Integer id);
3.2測試類
/**
* 測試@Query update
*/
@Test
@Transactional
@Rollback(false)
public void test10(){
this.usersDao.updateUserAgeById(24, 5);
}
五、 CrudRepository 接口
1 創建接口
package com.bjsxt.dao;
import org.springframework.data.repository.CrudRepository;
import com.bjsxt.pojo.Users;
/**
* CrudRepository接口講解
* @author Administrator
*
*/
public interface UsersDao extends CrudRepository<Users, Integer> {
}
2 測試代碼
package com.bjsxt.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.bjsxt.dao.UsersDao;
import com.bjsxt.pojo.Users;
/**
* CrudRepository接口測試
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 添加單條數據
*/
@Test
public void test1(){
Users user = new Users();
user.setUserage(21);
user.setUsername("趙小麗");
this.usersDao.save(user);
}
/**
* 批量添加數據
*/
@Test
public void test2(){
Users user = new Users();
user.setUserage(21);
user.setUsername("趙小麗");
Users user1 = new Users();
user1.setUserage(25);
user1.setUsername("王小虎");
List<Users> list= new ArrayList<>();
list.add(user);
list.add(user1);
this.usersDao.save(list);
}
/**
* 根據ID查詢單條數據
*/
@Test
public void test3(){
Users users = this.usersDao.findOne(13);
System.out.println(users);
}
/**
* 查詢全部數據
*/
@Test
public void test4(){
List<Users> list = (List<Users>)this.usersDao.findAll();
for (Users users : list) {
System.out.println(users);
}
}
/**
* 刪除數據
*/
@Test
public void test5(){
this.usersDao.delete(13);
}
/**
* 更新數據 方式一
*/
@Test
public void test6(){
Users user = this.usersDao.findOne(12);
user.setUsername("王小紅");
this.usersDao.save(user);
}
/**
* 更新數據 方式二
*/
@Test
@Transactional
@Rollback(false)
public void test7(){
Users user = this.usersDao.findOne(12);//持久化狀態的
user.setUsername("王小小");
}
}
六、 PagingAndSortingRepository 接口
1 分頁處理
1.1創建接口
package com.bjsxt.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.bjsxt.pojo.Users;
/**
* PagingAndSortingRepository接口講解
* @author Administrator
*
*/
public interface UsersDao extends PagingAndSortingRepository<Users, Integer>{
}
1.2測試代碼
package com.bjsxt.test;
import java.util.ArrayList;
import java.util.List;
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.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.bjsxt.dao.UsersDao;
import com.bjsxt.pojo.Users;
/**
* CrudRepository接口測試
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 分頁
*/
@Test
public void test1(){
int page = 2; //page:當前頁的索引。注意索引都是從0開始的。
int size = 3;// size:每頁顯示3條數據
Pageable pageable= new PageRequest(page, size);
Page<Users> p = this.usersDao.findAll(pageable);
System.out.println("數據的總條數:"+p.getTotalElements());
System.out.println("總頁數:"+p.getTotalPages());
List<Users> list = p.getContent();
for (Users users : list) {
System.out.println(users);
}
}
}
2 排序的處理
2.1測試代碼
/**
* 對單列做排序處理
*/
@Test
public void test2(){
//Sort:該對象封裝了排序規則以及指定的排序字段(對象的屬性來表示)
//direction:排序規則
//properties:指定做排序的屬性
Sort sort = new Sort(Direction.DESC,"userid");
List<Users> list = (List<Users>)this.usersDao.findAll(sort);
for (Users users : list) {
System.out.println(users);
}
}
/**
* 多列的排序處理
*/
@Test
public void test3(){
//Sort:該對象封裝了排序規則以及指定的排序字段(對象的屬性來表示)
//direction:排序規則
//properties:指定做排序的屬性
Order order1 = new Order(Direction.DESC,"userage");
Order order2 = new Order(Direction.ASC,"username");
Sort sort = new Sort(order1,order2);
List<Users> list = (List<Users>)this.usersDao.findAll(sort);
for (Users users : list) {
System.out.println(users);
}
}
七、 JpaRepository 接口
JpaRepository 接口是我們開發時使用的最多的接口。其特點是可以幫助我們將其他接口的方法的返回值做適配處理。可以使得我們在開發時更方便的使用這些方法
package com.bjsxt.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.bjsxt.pojo.Users;
/**
* JpaRepository接口講解
* @author Administrator
*
*/
public interface UsersDao extends JpaRepository<Users, Integer>{
}
2 測試代碼
package com.bjsxt.test;
import java.util.ArrayList;
import java.util.List;
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.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.bjsxt.dao.UsersDao;
import com.bjsxt.pojo.Users;
/**
* JpaRepository接口測試
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 查詢全部數據
*/
@Test
public void test1(){
List<Users> list = this.usersDao.findAll();
for (Users users : list) {
System.out.println(users);
}
}
}
八、 JpaSpecificationExecutor 接口--------完成多條件查詢,並且支持分頁與排序
注意:JpaSpecificationExecutor<Users>:不能單獨使用,需要配合着 jpa 中的其他接口一起使用
1 單條件查詢
1.1創建接口
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.bjsxt.pojo.Users;
/**
* JpaSpecificationExecutor接口講解
* @author Administrator
*注意:JpaSpecificationExecutor<Users>:不能單獨使用,需要配合着jpa中的其他接口一起使用
*/
public interface UsersDao extends JpaRepository<Users, Integer>,JpaSpecificationExecutor<Users>{
}
1.2測試代碼
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
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.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import com.bjsxt.dao.UsersDao;
import com.bjsxt.pojo.Users;
/**
* JpaRepository接口測試
* @author Administrator
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 需求:根據用戶姓名查詢數據
*/
@Test
public void test1(){
Specification<Users> spec = new Specification<Users>() {
/**
* @return Predicate:定義了查詢條件
* @param Root<Users> root:根對象。封裝了查詢條件的對象
* @param CriteriaQuery<?> query:定義了一個基本的查詢。一般不使用
* @param CriteriaBuilder cb:創建一個查詢條件
*/
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate pre = cb.equal(root.get("username"), "王五");
return pre;
}
};
List<Users> list = this.usersDao.findAll(spec);
for (Users users : list) {
System.out.println(users);
}
}
}
2 多條件查詢
2.1給定查詢條件方式一
/**
* 多條件查詢 方式一
* 需求:使用用戶姓名以及年齡查詢數據
*/
@Test
public void test2(){
Specification<Users> spec = new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> list = new ArrayList<>();
list.add(cb.equal(root.get("username"),"王五"));
list.add(cb.equal(root.get("userage"),24));
//此時條件之間是沒有任何關係的。
Predicate[] arr = new Predicate[list.size()];
return cb.and(list.toArray(arr));
}
};
List<Users> list = this.usersDao.findAll(spec);
for (Users users : list) {
System.out.println(users);
}
}
2.2給定查詢條件方式二
cb.like(root.get("username").as(String.class),"王%");
/**
* 多條件查詢 方式二
* 需求:使用用戶姓名或者年齡查詢數據
*/
@Test
public void test3(){
Specification<Users> spec = new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root,CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.or(cb.equal(root.get("username"),"王五"),cb.equal(root.get("userage"), 25));
}
};
List<Users> list = this.usersDao.findAll(spec);
for (Users users : list) {
System.out.println(users);
}
}
3 分頁
/**
* 需求:查詢王姓用戶,並且做分頁處理
*/
@Test
public void test4(){
//條件
Specification<Users> spec = new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.like(root.get("username").as(String.class), "王%");
}
};
//分頁
Pageable pageable = new PageRequest(2, 2);
Page<Users> page = this.usersDao.findAll(spec, pageable);
System.out.println("總條數:"+page.getTotalElements());
System.out.println("總頁數:"+page.getTotalPages());
List<Users> list = page.getContent();
for (Users users : list) {
System.out.println(users);
}
}
4 排序
/**
* 需求:查詢數據庫中王姓的用戶,並且根據用戶id做倒序排序
*/
@Test
public void test5(){
//條件
Specification<Users> spec = new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.like(root.get("username").as(String.class), "王%");
}
};
//排序
Sort sort = new Sort(Direction.DESC,"userid");
List<Users> list = this.usersDao.findAll(spec, sort);
for (Users users : list) {
System.out.println(users);
}
}
5 分頁與排序
/**
* 需求:查詢數據庫中王姓的用戶,做分頁處理,並且根據用戶id做倒序排序
*/
@Test
public void test6(){
//排序等定義
Sort sort = new Sort(Direction.DESC,"userid");
//分頁的定義
Pageable pageable = new PageRequest(2,2, sort);
//查詢條件
Specification<Users> spec = new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.like(root.get("username").as(String.class), "王%");
}
};
Page<Users> page = this.usersDao.findAll(spec, pageable);
System.out.println("總條數:"+page.getTotalElements());
System.out.println("總頁數:"+page.getTotalPages());
List<Users> list = page.getContent();
for (Users users : list) {
System.out.println(users);
}
}
九、 用戶自定義 Repository 接口
1 創建接口
package com.bjsxt.dao;
import com.bjsxt.pojo.Users;
public interface UsersRepository {
public Users findUserById(Integer userid);
}
2 使用接口
package com.bjsxt.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.bjsxt.pojo.Users;
/**
* 用戶自定義Repository接口講解
* @author Administrator
*/
public interface UsersDao extends JpaRepository<Users, Integer>,JpaSpecificationExecutor<Users>,UsersRepository{
}
3 創建接口實現類
package com.bjsxt.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import com.bjsxt.pojo.Users;
public class UsersDaoImpl implements UsersRepository {
@PersistenceContext(name="entityManagerFactory")
private EntityManager em;
@Override
public Users findUserById(Integer userid) {
System.out.println("MyRepository......");
return this.em.find(Users.class, userid);
}
}
4 編寫測試代碼
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
@Autowired
private UsersDao usersDao;
/**
* 需求:根據用戶ID查詢數據
*/
@Test
public void test1(){
Users users = this.usersDao.findUserById(5);
System.out.println(users);
}
}