SpringData JPA提供的五个接口及其简单实现

1.Repository接口
用户定义的dao接口继承Repository接口后即可根据方法命名规则或@Query查询对数据库进行操作
SpringData JPA提供的五个接口及其简单实现_第1张图片
UsersDao.java

package per.czt.dao;

import java.util.List;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;

import per.czt.pojo.Users;

public interface UsersDao extends Repository {

	//方法名称命名规则
	List findByUsernameIs(String username);

	List findByUsernameLike(String username);
	
	List findByUsernameAndUserageGreaterThanEqual(String username,Integer userage);
	//使用@Query注解查询,类似hql查询
	@Query(value="from Users where username=?")
	List queryUserByNameJPQL(String username);
	@Query(value="from Users where username like ?")
	List queryUsernameLikeJPQL(String username);
	@Query(value="from Users where username=? and userage>=?")
	List queryByUsernameAndUserageGreaterThanEqual(String username,Integer userage);
	
	//使用@Query进行SQL查询,要写nativeQuery=true
	@Query(value="select * from t_users where user_name=?",nativeQuery=true)
	List queryUserByUsernameUseSQL(String username);
	@Query(value="select * from t_users where user_name like ?",nativeQuery=true)
	List queryUsernameLikeUseSQL(String username);
	
	@Query(value="select * from t_users where user_name=? and user_age>=?",nativeQuery=true)
	List queryByUsernameAndUserageGreaterThanEqualUseSQL(String username,Integer userage);
	
	//使用@Query进行更新
	@Query(value="update Users set userage=? where userid=?")
	@Modifying//要写@Modifying
	void updateUsersByUserage(Integer userage,Integer userid);
}

RepositoryTest.java

package per.czt.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 per.czt.dao.UsersDao;
import per.czt.pojo.Users;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RepositoryTest {
	@Autowired
	private UsersDao usersDao;
	
	/*
	 * 判断相等
	 * 1.什么都不写
	 * 2.Is
	 * 3.Equal
	 * 
	 */
	@Test
	public void test1() {
		List usersList=usersDao.findByUsernameIs("李四");
		for(Users users:usersList) {
			System.out.println(users.toString());
		}
	}
	/*
	 * 对姓名做Like处理
	 * 
	 */
	@Test
	public void test2() {
		List usersList=usersDao.findByUsernameLike("李四%");
		for(Users users:usersList) {
			System.out.println(users.toString());
		}
	}
	/*
	 * 查询姓名为李四并且年龄大于等于28
	 */
	@Test
	public void test3() {
		List usersList=usersDao.findByUsernameAndUserageGreaterThanEqual("李四", 28);
		for(Users users:usersList) {
			System.out.println(users.toString());
		}
	}
	
	@Test
	public void test4() {
		List usersList=usersDao.queryUserByNameJPQL("李四");
		for(Users users:usersList) {
			System.out.println(users.toString());
		}
	}
	@Test
	public void test5() {
		List usersList=usersDao.queryUsernameLikeJPQL("李%");
		for(Users users:usersList) {
			System.out.println(users.toString());
		}
	}
	
	@Test
	public void test6() {
		List usersList=usersDao.queryByUsernameAndUserageGreaterThanEqual("李四", 20);
		for(Users users:usersList) {
			System.out.println(users.toString());
		}
	}
	
	@Test
	public void test7() {
		List usersList=usersDao.queryUserByUsernameUseSQL("张三");
		for(Users users:usersList) {
			System.out.println(users.toString());
		}
	}
	
	@Test
	public void test8() {
		List usersList=usersDao.queryUsernameLikeUseSQL("%三");
		for(Users users:usersList) {
			System.out.println(users.toString());
		}
	}
	
	@Test
	public void test9() {
		List usersList=usersDao.queryByUsernameAndUserageGreaterThanEqualUseSQL("张三", 1);
		for(Users users:usersList) {
			System.out.println(users.toString());
		}
	}
	
	@Test
	@Transactional
	@Rollback(false)
	//更新操作要进行事务提交
	public void test10() {
		usersDao.updateUsersByUserage(11, 4);
	}
	
	

}

2.CrudRepostory接口
对于简单的查询(根据主键查询,查询所有),还有插入、更新、删除操作用户无需自己定义,只需继承CrudRepostory接口即可调用相应的方法
UsersDao.java

package per.czt.dao;


import org.springframework.data.repository.CrudRepository;


import per.czt.pojo.Users;

public interface UsersDao extends CrudRepository {
}

CrudRepositoryTest.java

package per.czt.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 per.czt.dao.UsersDao;
import per.czt.pojo.Users;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class CrudRepositoryTest {
	@Autowired
	private UsersDao usersDao;
	@Test
	public void test() {
		
	}
	/*
	 * 添加
	 */
	 	//CrudRepository接口的save自己实现了事务
	@Test
	public void test1() {
		Users user=new Users();
		user.setUserage(12);
		user.setUsername("李明");
		usersDao.save(user);
	}
	/*
	 * 批量添加
	 */
	@Test
	//CrudRepository接口的save自己实现了事务
	public void test2() {
		Users user1=new Users();
		user1.setUserage(15);
		user1.setUsername("赵晓丽");
		
		Users user2=new Users();
		user2.setUserage(19);
		user2.setUsername("王小虎");
		
		Users user3=new Users();
		user3.setUserage(19);
		user3.setUsername("宋晓路");
		
		List usersList=new ArrayList();
		usersList.add(user1);
		usersList.add(user2);
		usersList.add(user3);
		
		usersDao.save(usersList);
		
	}
	/*
	 * 删除
	 */
	@Test
	public void test6() {
		this.usersDao.delete(10);
		
	}
	/*
	 * 根据主键查询
	 */

	@Test
	public void test4() {
		Users user=usersDao.findOne(15);
		System.out.println(user);
	}
	/*
	 * 查询所有
	 */
	@Test
	public void test5() {
		List usersList=(List) usersDao.findAll();
		for(Users user:usersList) {
			System.out.println(user);
		}
	}
	
	
	/*
	 * 更新-1
	 */
	@Test
	//CrudRepository接口的save自己实现了事务
	public void test7() {
		Users user=usersDao.findOne(14);
		user.setUsername("姜理");
		user.setUserage(10);
		usersDao.save(user);
	}

	/*
	 * 更新-2
	 */
	@Test
	@Transactional
	@Rollback(false)
	public void test8() {
		
		Users user=usersDao.findOne(6);
		//此时对象处于持久态
		
		user.setUsername("张三丰");
		
	}
}

3.PageAndSortingRepository接口
该接口提供了分页和排序的操作,和CrudRepository一样,只需继承该接口,就可以调用相应的方法
UsersDao.java

package per.czt.dao;



import org.springframework.data.repository.PagingAndSortingRepository;

import per.czt.pojo.Users;

public interface UsersDao extends PagingAndSortingRepository {
}

PageAndSortingRepositoryTest.java

package per.czt.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.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;


import per.czt.dao.UsersDao;
import per.czt.pojo.Users;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class PageAndSortingRepositoryTest {
	@Autowired
	private UsersDao usersDao;
	/*
	 * 分页
	 */
	@Test
	public void test() {
		int page=1;
		int size=3;
		Pageable pageable=new PageRequest(page,size);
		Page pages=this.usersDao.findAll(pageable);
		System.out.println("所有记录的数目:"+pages.getTotalElements());
		System.out.println("当前页的数目:"+pages.getSize());
		System.out.println("页的数目:"+pages.getTotalPages());
		List usersList=pages.getContent();
		for(Users user:usersList) {
			System.out.println(user);
		}
	}
	/*
	 * 排序
	 */
	@Test
	public void test2() {
		//Sort:该对象封装了排序规则以及制定的排序字段(对象的属性来表示)
		//direction:排序规则
		//properties:指定做排序的属性
		
		Sort sort=new Sort(Direction.DESC,"userid");
		
		List usersList=(List) this.usersDao.findAll(sort);
		for(Users user:usersList) {
			System.out.println(user);
		}
	}
	/*
	 * 多个排序规则的排序
	 */
	@Test
	public void test3() {
		Order order1=new Order(Direction.DESC,"username");
		Order order2=new Order(Direction.DESC,"userage");
		Sort sort=new Sort(order1,order2);
		List usersList=(List) this.usersDao.findAll(sort);
		for(Users user:usersList) {
			System.out.println(user);
		}
		
		
	}
	
	
}

4.JpaRepository接口
该接口对前面接口的返回值进行了适配处理,比如继承该接口后调用findAll方法直接返回List<实体>

UsersDao.java

package per.czt.dao;



import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;

import per.czt.pojo.Users;

public interface UsersDao extends JpaRepository {
}

JpaRepositoryTest.java

package per.czt.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.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;


import per.czt.dao.UsersDao;
import per.czt.pojo.Users;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JpaRepositoryTest {
	@Autowired
	private UsersDao usersDao;
	/*
	 * 查询所有
	 */
	@Test
	public void test() {
		List usersList=usersDao.findAll();
		for(Users user:usersList) {
			System.out.println(user);
		}
	}
	/*
	 * 分页
	 */
	@Test
	public void test2() {
		Pageable pageable=new PageRequest(0, 2);
		Page pages=usersDao.findAll(pageable);
		for(Users user:pages.getContent()) {
			System.out.println(user);
		}
		
		
	}
	
}

5.JpaSpecificationExecutor接口
该接口提供了多条件查询的方法,不单独使用,配合其他接口一起使用
UsersDao.java

package per.czt.dao;



import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;

import per.czt.pojo.Users;

public interface UsersDao extends JpaRepository,JpaSpecificationExecutor {
}

JpaSpecificationExectorTest.java

package per.czt.test;


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.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;



import per.czt.dao.UsersDao;
import per.czt.pojo.Users;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JpaSpecificationExectorTest {
	@Autowired
	private UsersDao usersDao;
	/*
	 * 单条件
	 */
	@Test
	public void test() {
		Specification spec=new Specification() {
			/*
			 * 
			 * (non-Javadoc)
			 * @see org.springframework.data.jpa.domain.Specification#toPredicate(javax.persistence.criteria.Root, javax.persistence.criteria.CriteriaQuery, javax.persistence.criteria.CriteriaBuilder)
			 *Predicate:定义了查询条件
			 *root:封装了查询条件的对象
			 * CriteriaQuery:定义了基本的查询功能,一般不使用
			 * CriteriaBuilder :创建一个查询条件
			 */

			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				Predicate cate=cb.equal(root.get("username"), "李四");
				
				return cate;
			}
		};
		List usersList=usersDao.findAll(spec);
		for(Users user:usersList) {
			System.out.println(user);
		}
		
	}
    /*
     * 多条件-1
     */
	@Test
	public void test2() {
		Specification spec=new Specification() {

			@Override
			public Predicate toPredicate(Root root, CriteriaQuery arg1, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				List predicateList=new ArrayList();
				predicateList.add(cb.equal(root.get("username"), "李四"));
				predicateList.add(cb.equal(root.get("userage"),28));
			
				//return cb.and(predicateList.get(0),predicateList.get(1));
				Predicate []arr=new Predicate[predicateList.size()];
				return cb.and(predicateList.toArray(arr));
			}
		};
		List usersList=usersDao.findAll(spec);
		for(Users user:usersList) {
			System.out.println(user);
		}
	}
	/*
	 * 多条件-2
	 */
	@Test
	public void test3() {
		Specification spec=new Specification() {
			
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				return cb.or(cb.equal(root.get("username"), "李四"),cb.equal(root.get("userage"), 15));
			}
		};
		List usersList=usersDao.findAll(spec);
		for(Users user:usersList) {
			System.out.println(user);
		}
	}
	/*
	 * 分页
	 */
	
	@Test
	public void test4() {
       Specification spec=new Specification() {
			
			@Override
			public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				return cb.like(root.get("username").as(String.class), "王%");
			}
		};
		Pageable pageable=new PageRequest(0,2);
		Page pages= usersDao.findAll(spec,pageable);
		List usersList=pages.getContent();
		for(Users user:usersList) {
			System.out.println(user);
		}
		
	}
	/*
	 * 排序
	 */
	@Test
	public void test5() {
		Specification spec=new Specification() {

			@Override
			public Predicate toPredicate(Root root, CriteriaQuery arg1, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				return cb.like(root.get("username").as(String.class), "李%");
			}
		};
		Order order1=new Order(Direction.ASC,"username");
		Order order=new Order(Direction.DESC,"userage");
		
		Sort sort=new Sort(order1,order);
		
		List usersList=usersDao.findAll(spec, sort);
		for(Users user:usersList) {
			System.out.println(user);
		}
	}
	/*
	 * 分页+排序
	 */
	@Test
	public void test6() {
		
		Specification spec=new Specification() {

			@Override
			public Predicate toPredicate(Root root, CriteriaQuery arg1, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				return cb.like(root.get("username").as(String.class), "李%");
			}
		};
		Sort sort=new Sort(new Order(Direction.ASC,"username"),new Order(Direction.DESC,"userage"));
		
		Pageable pageable=new PageRequest(1, 2, sort);
		Page pages=usersDao.findAll(spec, pageable);
		List usersList=pages.getContent();
		for(Users user:usersList) {
			System.out.println(user);
		}
		
	}
}

你可能感兴趣的:(Spring,Data)