SpringData----Spring Data JPA(上)

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);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值