org.springframework
spring-orm
5.1.6.RELEASE
org.springframework
spring-context
5.1.6.RELEASE
org.aspectj
aspectjweaver
1.9.2
com.alibaba
druid
1.1.8
mysql
mysql-connector-java
8.0.11
org.hibernate
hibernate-core
5.0.7.Final
junit
junit
4.12
test
org.springframework
spring-test
5.1.6.RELEASE
true
update
com.bobo.pojo
package com.bobo.pojo;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name="t_user")
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id")
private Integer userId;
@Column(name="user_name")
private String userName;
@Column(name="real_name")
private String realName;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
package com.bobo.dao;
import com.bobo.pojo.Users;
import java.util.List;
public interface IUserDao {
void insertUsers(Users users);
void updateUsers(Users users);
void deleteUsers(Users users);
Users selectUsersById(Integer userId);
List selectUsersByName(String userName);
List selectUsersByNameUseSQL(String userName);
List selectUsersByNameUseCriteria(String userName);
}
package com.bobo.dao.impl;
import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class UserDaoImpl implements IUserDao {
@Autowired
private HibernateTemplate template;
@Override
public void insertUsers(Users users) {
this.template.save(users);
}
@Override
public void updateUsers(Users users) {
this.template.update(users);
}
@Override
public void deleteUsers(Users users) {
this.template.delete(users);
}
@Override
public Users selectUsersById(Integer userId) {
return this.template.get(Users.class,userId);
}
@Override
public List selectUsersByName(String userName) {
// 我们要执行特殊的查询操作 我们需要获取对应的Session对象
Session session = this.template.getSessionFactory().getCurrentSession();
// 通过Session对象创建Query对象 HQL 语句
Query query = session.createQuery(" from Users where userName = :abc");
Query queryTemp = query.setString("abc", userName);
return queryTemp.list();
}
@Override
public List selectUsersByNameUseSQL(String userName) {
// 我们要执行特殊的查询操作 我们需要获取对应的Session对象
Session session = this.template.getSessionFactory().getCurrentSession();
// 通过Session对象创建Query对象 SQL 语句
Query query = session.createSQLQuery("select * from t_user where user_name = ?")
.addEntity(Users.class)
.setString(0, userName);
return query.list();
}
@Override
public List selectUsersByNameUseCriteria(String userName) {
Session session = this.template.getSessionFactory().getCurrentSession();
Criteria criteria = session.createCriteria(Users.class);
criteria.add(Restrictions.eq("userName",userName));
return criteria.list();
}
}
package com.bobo.test;
import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
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 java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {
@Autowired
private IUserDao dao;
@Test
@Transactional
@Rollback(false)
public void testInsertUser(){
Users user = new Users();
user.setUserName("Tom");
user.setRealName("张三丰");
dao.insertUsers(user);
}
@Test
@Transactional
public void testQuery1(){
Users users = this.dao.selectUsersById(22);
System.out.println(users);
}
@Test
@Transactional
public void testQuery2(){
List list = this.dao.selectUsersByNameUseSQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
}
org.springframework
spring-orm
5.1.6.RELEASE
org.springframework
spring-context
5.1.6.RELEASE
org.aspectj
aspectjweaver
1.9.2
com.alibaba
druid
1.1.8
mysql
mysql-connector-java
8.0.11
org.hibernate
hibernate-entitymanager
5.0.7.Final
junit
junit
4.12
test
org.springframework
spring-test
5.1.6.RELEASE
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
com.bobo.pojo
package com.bobo.pojo;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name="t_user")
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id")
private Integer userId;
@Column(name="user_name")
private String userName;
@Column(name="real_name")
private String realName;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
@Override
public String toString() {
return "Users{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", realName='" + realName + '\'' +
'}';
}
}
package com.bobo.dao;
import com.bobo.pojo.Users;
import java.util.List;
public interface IUserDao {
void insertUsers(Users users);
void updateUsers(Users users);
void deleteUsers(Users users);
Users selectUsersById(Integer userId);
List selectUsersByName(String userName);
List selectUsersByNameUseSQL(String userName);
List selectUsersByNameUseCriteria(String userName);
}
package com.bobo.dao.impl;
import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;
@Repository
public class UserDaoImpl implements IUserDao {
@PersistenceContext(name = "entityManagerFactory")
private EntityManager manager;
@Override
public void insertUsers(Users users) {
manager.persist(users);
}
@Override
public void updateUsers(Users users) {
manager.merge(users);
}
@Override
public void deleteUsers(Users users) {
users = this.selectUsersById(users.getUserId());
manager.remove(users);
}
@Override
public Users selectUsersById(Integer userId) {
return manager.find(Users.class,userId);
}
@Override
public List selectUsersByName(String userName) {
return manager.createQuery(" from Users where userName = :abc")
.setParameter("abc",userName)
.getResultList();
}
@Override
public List selectUsersByNameUseSQL(String userName) {
return manager.createNativeQuery("select * from t_user where user_name = ?",Users.class)
.setParameter(1,userName)
.getResultList();
}
@Override
public List selectUsersByNameUseCriteria(String userName) {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery(Users.class);
Root root = query.from(Users.class);
Predicate cate = builder.equal(root.get("userName"), userName);
query.where(cate);
TypedQuery typedQuery = manager.createQuery(query);
return typedQuery.getResultList();
}
}
package com.bobo.test;
import com.bobo.dao.IUserDao;
import com.bobo.pojo.Users;
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 java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {
@Autowired
private IUserDao dao;
@Test
@Transactional
@Rollback(false)
public void testInsertUser(){
Users user = new Users();
user.setUserName("Mic");
user.setRealName("李逵");
dao.insertUsers(user);
}
@Test
@Transactional
public void testQuery1(){
Users users = this.dao.selectUsersById(22);
System.out.println(users);
}
@Test
@Transactional
public void testQuery2(){
List list = this.dao.selectUsersByNameUseSQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
}
org.springframework
spring-orm
5.1.6.RELEASE
org.springframework
spring-context
5.1.6.RELEASE
org.aspectj
aspectjweaver
1.9.2
com.alibaba
druid
1.1.8
mysql
mysql-connector-java
8.0.11
org.hibernate
hibernate-entitymanager
5.0.7.Final
junit
junit
4.12
test
org.springframework
spring-test
5.1.6.RELEASE
org.springframework.data
spring-data-jpa
1.9.0.RELEASE
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/logistics?characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
com.bobo.pojo
package com.bobo.pojo;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name="t_user")
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id")
private Integer userId;
@Column(name="user_name")
private String userName;
@Column(name="real_name")
private String realName;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
@Override
public String toString() {
return "Users{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", realName='" + realName + '\'' +
'}';
}
}
package com.bobo.dao;
import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao extends JpaRepository {
}
package com.bobo.test;
import com.bobo.dao.UserDao;
import com.bobo.pojo.Users;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test1 {
@Autowired
private UserDao dao;
@Test
@Transactional
@Rollback(false)
public void test1(){
Users user = new Users();
user.setUserName("admin-jpa");
user.setRealName("测试");
dao.save(user);
}
}
public interface Repository {
}
package com.bobo.dao;
import com.bobo.pojo.Users;
import org.springframework.data.repository.Repository;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;
/**
* Repository接口的使用
*/
public interface UserDaoRepository extends Repository {
List findByUserNameIs(String string);
List findByUserNameLike(String username);
List findByUserNameAndRealNameIs(String name,String realName);
}
package com.bobo.test;
import com.bobo.dao.UserDaoRepository;
import com.bobo.pojo.Users;
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 java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test2 {
@Autowired
private UserDaoRepository dao;
@Test
@Transactional
@Rollback(false)
public void query1(){
List list = this.dao.findByUserNameIs("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query2(){
List list = this.dao.findByUserNameLike("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query3(){
List list = this.dao.findByUserNameAndRealNameIs("Tom","张三丰");
for (Users users : list) {
System.out.println(users);
}
}
}
package com.bobo.dao;
import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import java.util.List;
/**
* Repository接口的使用
* @Query
* JPQL语句
* SQL语句
* 更新操作
*/
public interface UserDaoRepository2 extends Repository {
@Query(value = " from Users where userName =?")
List queryUsersByNameUseJPQL(String name);
@Query(value = " from Users where userName like ?")
List queryUserLikeNameUseJPQL(String name);
@Query(value = " from Users where userName= ? and realName = ?")
List queryUserByNameAndRealName(String userName,String realName);
}
package com.bobo.test;
import com.bobo.dao.UserDaoRepository;
import com.bobo.dao.UserDaoRepository2;
import com.bobo.pojo.Users;
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 java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test3 {
@Autowired
private UserDaoRepository2 dao;
@Test
@Transactional
@Rollback(false)
public void query1(){
List list = this.dao.queryUsersByNameUseJPQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query2(){
List list = this.dao.queryUserLikeNameUseJPQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query3(){
List list = this.dao.queryUserByNameAndRealName("Tom","张三丰");
for (Users users : list) {
System.out.println(users);
}
}
}
package com.bobo.dao;
import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import java.util.List;
/**
* Repository接口的使用
* @Query
* JPQL语句
* SQL语句
* 更新操作
*/
public interface UserDaoRepository3 extends Repository {
// 在使用@Query注解 查询SQL语句的时候 nativeQuery默认是false,我们需要设置为true
@Query(value = "select * from t_user where user_name=?",nativeQuery = true)
List queryUsersByNameUseSQL(String name);
@Query(value = "select * from t_user where user_name like ?" ,nativeQuery = true)
List queryUserLikeNameUseSQL(String name);
@Query(value = "select * from t_user where user_name = ? and real_name = ?" , nativeQuery = true)
List queryUserByNameAndRealName(String userName,String realName);
}
package com.bobo.test;
import com.bobo.dao.UserDaoRepository2;
import com.bobo.dao.UserDaoRepository3;
import com.bobo.pojo.Users;
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 java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test4 {
@Autowired
private UserDaoRepository3 dao;
@Test
@Transactional
@Rollback(false)
public void query1(){
List list = this.dao.queryUsersByNameUseSQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query2(){
List list = this.dao.queryUserLikeNameUseSQL("Tom");
for (Users users : list) {
System.out.println(users);
}
}
@Test
@Transactional
@Rollback(false)
public void query3(){
List list = this.dao.queryUserByNameAndRealName("Tom","张三丰");
for (Users users : list) {
System.out.println(users);
}
}
}
@Query(value = "update Users set userName = ? where userId=?")
@Modifying// 被@Modifying修饰的方法是一个更新操作
void updateUserNameById(String userName,Integer userId);
@Test
@Transactional
@Rollback(false)
public void updateTest(){
this.dao.updateUserNameById("Tommm",25);
}
@NoRepositoryBean
public interface CrudRepository extends Repository {
S save(S var1);
Iterable save(Iterable var1);
T findOne(ID var1);
boolean exists(ID var1);
Iterable findAll();
Iterable findAll(Iterable var1);
long count();
void delete(ID var1);
void delete(T var1);
void delete(Iterable extends T> var1);
void deleteAll();
}
/**
* CrudRepository接口的使用
*/
public interface UserDaoCrudRepository extends CrudRepository {
}
package com.bobo.test;
import com.bobo.dao.UserDaoCrudRepository;
import com.bobo.dao.UserDaoRepository3;
import com.bobo.pojo.Users;
import org.junit.Test;
import org.junit.experimental.theories.suppliers.TestedOn;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.CustomSQLErrorCodesTranslation;
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 java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test5 {
@Autowired
private UserDaoCrudRepository dao;
/**
* 添加数据
*/
@Test
public void test1(){
Users user = new Users();
user.setRealName("成龙");
user.setUserName("chengnong");
dao.save(user);
}
/**
* 批量添加数据
*/
@Test
public void test2(){
List list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Users user = new Users();
user.setRealName("成龙"+i);
user.setUserName("chengnong"+i);
list.add(user);
}
dao.save(list);
}
/**
* 查询单条数据
*/
@Test
public void test3(){
Users user = dao.findOne(25);
System.out.println(user);
}
/**
* 查询所有的数据
*/
@Test
public void test4(){
Iterable list = dao.findAll();
Iterator iterator = list.iterator();
while(iterator.hasNext()){
Users user = iterator.next();
System.out.println(user);
}
}
/**
* 删除数据
*/
@Test
public void delete1(){
dao.delete(32);
}
/**
* 更新数据
*/
@Test
public void update1(){
// 根据save方法来实现 如果Users对象的userId属性不为空则update
Users user = dao.findOne(34);
user.setUserName("hahahaha");
dao.save(user);
}
/**
* 更新数据 方式二
*/
@Test
@Transactional
@Rollback(false)
public void update2(){
Users user = dao.findOne(34);
user.setUserName("aaaa"); // User 是一个持久化的状态
}
}
@NoRepositoryBean
public interface PagingAndSortingRepository extends CrudRepository {
// 排序的支持
Iterable findAll(Sort var1);
// 分页的支持
Page findAll(Pageable var1);
}
package com.bobo.dao;
import com.bobo.pojo.Users;
import org.springframework.data.repository.PagingAndSortingRepository;
/**
* PagingAndSortingRepository接口的使用
* 新增的功能是
* 分页
* 排序
* 注意本接口不支持条件查询
*/
public interface UserDaoPageAndSortRepository extends PagingAndSortingRepository {
}
package com.bobo.test;
import com.bobo.dao.UserDaoCrudRepository;
import com.bobo.dao.UserDaoPageAndSortRepository;
import com.bobo.pojo.Users;
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.Sort;
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 java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test6 {
@Autowired
private UserDaoPageAndSortRepository dao;
/**
* 分页查询
*/
@Test
public void test1(){
int page = 1; // page:当前分页的索引 从0开始
int size = 5; // size:每页显示的条数
PageRequest pageable = new PageRequest(page,size);
Page pages = dao.findAll(pageable);
System.out.println("总的条数:" + pages.getTotalElements());
System.out.println("总的页数:" + pages.getTotalPages());
List list = pages.getContent();
for (Users user : list) {
System.out.println(user);
}
}
}
/**
* 排序
*/
@Test
public void test2(){
// Sort.Direction.DESC 降序 ASC 升序
Sort sort = new Sort(Sort.Direction.DESC,"userId");
List list = (List) this.dao.findAll(sort);
for (Users users : list) {
System.out.println(users);
}
}
/**
* 多条件排序
*/
@Test
public void test3(){
Sort.Order order1 = new Sort.Order(Sort.Direction.DESC,"realName");
Sort.Order order2 = new Sort.Order(Sort.Direction.ASC,"userId");
Sort sort = new Sort(order1,order2);
List list = (List) this.dao.findAll(sort);
for (Users users : list) {
System.out.println(users);
}
}
@NoRepositoryBean
public interface JpaRepository extends PagingAndSortingRepository {
List findAll();
List findAll(Sort var1);
List findAll(Iterable var1);
List save(Iterable var1);
void flush();
S saveAndFlush(S var1);
void deleteInBatch(Iterable var1);
void deleteAllInBatch();
T getOne(ID var1);
}
/**
* JpaSpecificationExecutor的使用
* JpaSpecificationExecutor 是不能够单独使用的。需要配置JPA中的其他的接口一块来使用
*/
public interface UserDaoSpecfication extends JpaRepository, JpaSpecificationExecutor {
}
package com.bobo.test;
import com.bobo.dao.UserDaoSpecfication;
import com.bobo.pojo.Users;
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.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test7 {
@Autowired
private UserDaoSpecfication dao;
@Test
public void test1(){
Specification speci = new Specification() {
/**
* 定义查询条件
* @param root 根对象 封装查询条件的对象
* @param criteriaQuery 基本的查询
* @param criteriaBuilder 创建查询条件
* @return
*/
@Override
public Predicate toPredicate(Root root
, CriteriaQuery> criteriaQuery
, CriteriaBuilder criteriaBuilder) {
Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
return pre;
}
};
List list = dao.findAll(speci);
for (Users users : list) {
System.out.println(users);
}
}
}
/**
* 多条件查询
*/
@Test
public void test2(){
Specification spec = new Specification() {
/**
* 指定查询的条件
* @param root
* @param criteriaQuery
* @param criteriaBuilder
* @return
*/
@Override
public Predicate toPredicate(Root root, CriteriaQuery> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List list = new ArrayList<>();
list.add(criteriaBuilder.equal(root.get("userName"),"Tommm"));
list.add(criteriaBuilder.equal(root.get("realName"),"张三丰"));
Predicate[] arr = new Predicate[list.size()];
return criteriaBuilder.and(list.toArray(arr));
}
};
List list = dao.findAll(spec);
for (Users users : list) {
System.out.println(users);
}
}
/**
* 单条件+分页
*/
@Test
public void test3(){
Specification speci = new Specification() {
/**
* 定义查询条件
* @param root 根对象 封装查询条件的对象
* @param criteriaQuery 基本的查询
* @param criteriaBuilder 创建查询条件
* @return
*/
@Override
public Predicate toPredicate(Root root
, CriteriaQuery> criteriaQuery
, CriteriaBuilder criteriaBuilder) {
Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
return pre;
}
};
Pageable pagealbe = (Pageable) new PageRequest(0,3);
Page page = dao.findAll(speci, pagealbe);
System.out.println(page.getTotalElements());
System.out.println(page.getTotalPages());
List content = page.getContent();
System.out.println(content);
}
/**
* 单条件+排序
*/
@Test
public void test4(){
Specification speci = new Specification() {
/**
* 定义查询条件
* @param root 根对象 封装查询条件的对象
* @param criteriaQuery 基本的查询
* @param criteriaBuilder 创建查询条件
* @return
*/
@Override
public Predicate toPredicate(Root root
, CriteriaQuery> criteriaQuery
, CriteriaBuilder criteriaBuilder) {
Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
return pre;
}
};
Sort sort = new Sort(Sort.Direction.DESC,"userId");
List list = dao.findAll(speci, sort);
System.out.println(list);
}
/**
* 单条件+分页 + 排序
*/
@Test
public void test5(){
Specification speci = new Specification() {
/**
* 定义查询条件
* @param root 根对象 封装查询条件的对象
* @param criteriaQuery 基本的查询
* @param criteriaBuilder 创建查询条件
* @return
*/
@Override
public Predicate toPredicate(Root root
, CriteriaQuery> criteriaQuery
, CriteriaBuilder criteriaBuilder) {
Predicate pre = criteriaBuilder.equal(root.get("userName"),"Tommm");
return pre;
}
};
Sort sort = new Sort(Sort.Direction.DESC,"userId");
// 封装分页对象的时候我们可以直接指定 排序的规则
Pageable pagealbe = (Pageable) new PageRequest(0,3,sort);
Page page = dao.findAll(speci, pagealbe);
System.out.println(page.getTotalElements());
System.out.println(page.getTotalPages());
List content = page.getContent();
System.out.println(content);
}
# jdbc 的相关信息
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/logistics?
characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
# 配置连接池信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 配置jpa的相关参数
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
package com.bobo.pojo;
import javax.persistence.*;
import java.io.Serializable;
@Table(name = "t_user")
@Entity
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id")
private Integer userId;
@Column(name="user_name")
private String usreName;
@Column(name="real_name")
private String realName;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsreName() {
return usreName;
}
public void setUsreName(String usreName) {
this.usreName = usreName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
}
package com.bobo.dao;
import com.bobo.pojo.Users;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UsersRepository extends JpaRepository {
}
package com.bobo;
import com.bobo.dao.UsersRepository;
import com.bobo.pojo.Users;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringdatajpaSpringbootApplicationTests {
@Autowired
private UsersRepository dao;
@Test
void contextLoads() {
Users users = new Users();
users.setUsreName("test1");
users.setRealName("测试数据");
dao.save(users);
}
}