文章目录
一、springboot中spring data jpa的配置
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xym</groupId>
<artifactId>jpa-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
application.yml
spring:
datasource:
url: jdbc:mysql://192.168.1.70:3306/jpa
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update # update 拥有表结构就什么也不做,create不管有没有都重新创建,create-drop 退出时清空表 none 什么也不做
show-sql: true #配置打印sql语句
database: mysql #指明数据库
properties:
hibernate.dialect: org.hibernate.dialect.MySQL55Dialect #设置hibernate数据库的方言
测试类基础模板
@RunWith(SpringRunner.class)
@SpringBootTest
public class ObjectQuery {
@Autowired
private Dao dao;
}
二、spring data jpa基础增删改查
实体bean
@Entity
@Table(name="t_book")
//@DynamicInsert
//@DynamicUpdate(value = true)//只对于更新的字段设置值
public class Book {
@Id //id表明是主键
//IDENTITY:主键由数据库自动生成(主要是自动增长型) mysql
//SEQUENCE:根据底层数据库的序列来生成主键,条件是数据库支持序列。
//AUTO:主键由程序控制
//TABLE:使用一个特定的数据库表格来保存主键
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//Column注解可以定制表中的字段属性 name 表示字段名称 nullable表示非空
@Column(name = "book_name",nullable = false)
private String name;
private Double price;
//自动开启了驼峰配置
private String bookAuthor;
@Transient //表示生成表的时候,该属性被忽略,不生成相应字段
private String description;
}
dao层代码
public interface BookDao extends JpaRepository<Book,Long>, JpaSpecificationExecutor<Book> {
}
测试代码
@Autowired
private BookDao bookDao;
@Test
@Transactional //测试懒加载,需要事务的支持
public void Test(){
//org.hibernate.LazyInitializationException: could not initialize proxy [com.xym.pojo.Book#1] - no Session
Book one = bookDao.getOne( 1L);//懒加载什么时候用是么时候查询
System.out.println(one);
}
@Test //查询实时生效
public void Test2(){
Optional<Book> byId = bookDao.findById(1L);
}
@Test//测试保存
public void save(){
Book book = new Book("四世同堂",5.88,"老舍");
bookDao.save(book);
System.out.println(book.getId());
}
@Test//测试更新
public void update(){
Optional<Book> book = bookDao.findById(9L);
/*Book book = new Book("骆驼",null,"老舍");
book.setId(9L);*/
Book book1 = book.get();
book1.setName("祥子");
book1.setBookAuthor("老舍");
bookDao.save(book1);
//System.out.println(book.getId());
}
三、spring data jpa利用原生sql或者jpql执行数据库操作
dao层代码
public interface BookDao extends JpaRepository<Book,Long>, JpaSpecificationExecutor<Book> {
/*//利用jpql或者sql语句完成查询
参数的接收方式分为两种:
一、按照参数的标识来传递参数
二、按照参数的位置来传递参数
*/
@Query(value = "select * from t_book b where b.id = :id and b.book_author =:author",nativeQuery = true)
List<Book> getBooksByIdAndAuthorByParam(@Param("author") String author, @Param("id") Long id);
@Query(value = "select * from t_book b where b.id = ?2 and b.book_author =?1",nativeQuery = true)
List<Book> getBooksByIdAndAuthorByPlace( String author, Long id);
@Query(value = "from Book b where b.id = ?2 and b.bookAuthor =?1")
List<Book> getBooksByIdAndAuthorByPlaceJPQL( String author, Long id);
@Modifying//利用次注解表明需要加入事务
@Query(value = "update Book b set b.bookAuthor =?1 where b.id=?2")
int updateBookAuthorById( String author,Long id);
}
测试部分代码
@Test//参数标识接收参数的方式
public void nativeParam1(){
List<Book> books = bookDao.getBooksByIdAndAuthorByParam("老舍", 9L);
for (Book b:
books) {
System.out.println(b);
}
}
@Test//参数接收方式
public void nativeParam2(){
List<Book> books = bookDao.getBooksByIdAndAuthorByPlace("老舍", 8L);
for (Book b:
books) {
System.out.println(b);
}
//System.out.println(book.getId());
}
@Test//参数标识接收参数的方式
public void jPQLParam1(){
List<Book> books = bookDao.getBooksByIdAndAuthorByPlaceJPQL("老舍", 9L);
for (Book b:
books) {
System.out.println(b);
}
}
@Test//利用sql语句或者jpql语句完成更新
@Transactional
@Rollback(value = false)
public void jPQLUpdate(){
bookDao.updateBookAuthorById("张三",7l);
}
四、spring data jpa根据命名规则查询
dao层代码
public interface BookDao extends JpaRepository<Book,Long>, JpaSpecificationExecutor<Book> {
/*
* 方法名的约定:
* findBookBy:表示单数
* findBooksBy:表示查询复数
* 1.findBy | getBy + 属性名称 (根据属性名称进行精确匹配的查询=)
* 2.findBy | getBy + 属性名称 + “查询方式(Like | isnull)”
* findByCustNameLike
* 3.多条件查询
* findBy | getBy + 属性名 + “查询方式” + “多条件的连接符(and|or)” + 属性名 + “查询方式”
*
* */
//1.findBy | getBy + 属性名称 (根据属性名称进行精确匹配的查询=)
Book findByName(String name);
//findBy | getBy + 属性名称 + “查询方式(Like | isnull)”
List<Book> getBooksByBookAuthorStartingWith(String author);
// findBy | getBy + 属性名 + “查询方式” + “多条件的连接符(and|or)” + 属性名 + “查询方式”
List<Book> findByNameLikeAndAndBookAuthor(String name,String bookAuthor);
}
测试代码
@Test//1.findBy | getBy + 属性名称 (根据属性名称进行精确匹配的查询=)
public void nameFindName(){
Book name = bookDao.findByName("三国演义");
System.out.println(name);
}
@Test//2.findBy | getBy + 属性名称 + “查询方式(Like | isnull)”
public void nameFindAuthorStart(){
List<Book> books = bookDao.getBooksByBookAuthorStartingWith("张");
System.out.println(books);
}
@Test//2.findBy | getBy + 属性名称 + “查询方式(Like | isnull)”
public void nameComponet(){
List<Book> books = bookDao.findByNameLikeAndAndBookAuthor("%祥子%","老舍");
System.out.println(books);
}
注:支持的命名规范:
五、specification(规范查询,分页,动态sql)
规范查询代码
@Test
public void testSpec() {
//匿名内部类
/**
* 自定义查询条件
* 1.实现Specification接口(提供泛型:查询的对象类型)
* 2.实现toPredicate方法(构造查询条件)
* 3.需要借助方法参数中的两个参数(
* root:获取需要查询的对象属性
* CriteriaBuilder:构造查询条件的,内部封装了很多的查询条件(模糊匹配,精准匹配)
* )
* 案例:根据客户名称查询,查询客户名为传智播客的客户
* 查询条件
* 1.查询方式
* cb对象
* 2.比较的属性名称
* root对象
*
*/
Specification<Book> spec = (Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb)-> {
//1.获取比较的属性
Path<Object> name = root.get("name");
//第二个参数:当前需要比较的取值
Predicate predicate = cb.equal(name, "朝花夕拾");
/*@Override
public Predicate toPredicate(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Path<Object> custName = root.get("custId");
//2.构造查询条件 : select * from cst_customer where cust_name = '传智播客'
*//**
* 第一个参数:需要比较的属性(path对象)
*
*//*
Predicate predicate = cb.equal(custName, "传智播客");//进行精准的匹配 (比较的属性,比较的属性的取值)
return predicate;
}*/
return predicate;
};
Book customer = bookDao.findOne(spec).get();
System.out.println(customer);
}
@Test
public void testSpec2(){
Specification<Book> spec =(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb)-> {
Path<Object> name = root.get("name");
Path<Object> bookAuthor = root.get("bookAuthor");
Predicate name1 = cb.equal(name,"骆驼祥子");
//name1.
Predicate bookAuthor1 = cb.equal(bookAuthor, "老舍");
Predicate and = cb.or(name1, bookAuthor1);
return and;
};
List<Book> all = bookDao.findAll(spec);
System.out.println(all);
}
@Test
public void testSpec3(){
Specification<Book> spec =(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb)-> {
Path<Object> name = root.get("name");
Predicate predicate = cb.like(name.as(String.class),"%祥子%");
return predicate;
};
//排序查询
Sort sort =new Sort(Sort.Direction.DESC,"id");
List<Book> all = bookDao.findAll(spec,sort);
System.out.println(all);
}
@Test
public void testSpec4(){
Specification<Book> spec =(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb)-> {
Path<Object> id = root.get("id");
Predicate predicate = cb.gt(id.as(Long.class),0L);
return predicate;
};
//排序查询
Sort sort =new Sort(Sort.Direction.DESC,"id");
Pageable page = PageRequest.of(0,2,sort);
Page<Book> all = bookDao.findAll(spec, page);
System.out.println(all.getTotalPages());
System.out.println(all.getTotalElements());
System.out.println(all.getContent());
}
@Test
public void testSpec5(){
String name = "骆驼祥子";
String bookAuthor = "老舍";
Specification<Book> spec =(Root<Book> root, CriteriaQuery<?> query, CriteriaBuilder cb)-> {
List<Predicate> pres = new ArrayList<>();
pres.add(cb.equal(root.get("name"),name));
pres.add(cb.equal(root.get("bookAuthor"),bookAuthor));
Predicate and = cb.and(pres.toArray(new Predicate[pres.size()]));
return and;
};
//排序查询
Sort sort =new Sort(Sort.Direction.DESC,"id");
Pageable page = PageRequest.of(0,2,sort);
Page<Book> all = bookDao.findAll(spec, page);
System.out.println(all.getTotalPages());
System.out.println(all.getTotalElements());
System.out.println(all.getContent());
}
六、多表关联查询
一对多查询
实体类
@Entity
@Table(name = "cst_customer")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="cust_id")
private Long custId;
@Column(name="cust_address")
private String custAddress;
@Column(name="cust_industry")
private String custIndustry;
@Column(name="cust_level")
private String custLevel;
@Column(name="cust_name")
private String custName;
@Column(name="cust_phone")
private String custPhone;
@Column(name="cust_source")
private String custSource;
//配置客户和联系人之间的关系(一对多关系)
/**
* 使用注解的形式配置多表关系
* 1.声明关系
* @OneToMany : 配置一对多关系
* targetEntity :对方对象的字节码对象
* 2.配置外键(中间表)
* @JoinColumn : 配置外键
* name:外键字段名称
* referencedColumnName:参照的主表的主键字段名称
*
* * 在客户实体类上(一的一方)添加了外键了配置,所以对于客户而言,也具备了维护外键的作用
*
*/
/*@OneToMany(targetEntity = LinkMan.class,cascade = CascadeType.ALL)
@JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
private Set<LinkMan> linkMans = new HashSet<>();*/
/*@OneToMany(mappedBy ="customer")
private Set<LinkMan> linkMans = new HashSet<>();*/
@OneToMany(mappedBy ="customer",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private Set<LinkMan> linkMans = new HashSet<>();
}
@Entity(name = "cst_linkman")
public class LinkMan {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "lkm_id")
private Long lkmId; //联系人编号(主键)
@Column(name = "lkm_name")
private String lkmName;//联系人姓名
@Column(name = "lkm_gender")
private String lkmGender;//联系人性别
@Column(name = "lkm_phone")
private String lkmPhone;//联系人办公电话
@Column(name = "lkm_mobile")
private String lkmMobile;//联系人手机
@Column(name = "lkm_email")
private String lkmEmail;//联系人邮箱
@Column(name = "lkm_position")
private String lkmPosition;//联系人职位
@Column(name = "lkm_memo")
private String lkmMemo;//联系人备注
/**
* 配置联系人到客户的多对一关系
* 使用注解的形式配置多对一关系
* 1.配置表关系
* @ManyToOne : 配置多对一关系
* targetEntity:对方的实体类字节码
* 2.配置外键(中间表)
*
* * 配置外键的过程,配置到了多的一方,就会在多的一方维护外键
*
*/
@ManyToOne(targetEntity = Customer.class,fetch = FetchType.LAZY)
@JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")
private Customer customer;
}
dao层代码
只是简单的实现两个接口不做特殊说明
查询的代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class OneToManyTest {
@Autowired
private CustomerDao customerDao;
@Autowired
private LinkManDao linkManDao;
@Test
@Transactional
@Rollback(value = false)
public void testAdd(){//通过客户表关联联系人
Customer c = new Customer();
c.setCustName("公信科技");
LinkMan linkMan = new LinkMan();
linkMan.setLkmName("肿瘤医院");
c.getLinkMans().add(linkMan);
//保存两条会多出一条update语句,原因是两个表都对外建进行了维护
//设置级联后保存一个,就可以把两条数据都进行保存
//customerDao.save(c);
//linkManDao.save(linkMan);
//有一方放弃外建的维护
customerDao.save(c);
linkManDao.save(linkMan);
}
@Test
@Transactional
@Rollback(value = false)
public void testAdd2(){//通过联系人关联客户
Customer c = new Customer();
c.setCustName("公信科技");
LinkMan linkMan = new LinkMan();
linkMan.setLkmName("肿瘤医院");
linkMan.setCustomer(c);
//有一方放弃外建的维护
customerDao.save(c);
linkManDao.save(linkMan);
}
@Test
@Transactional
@Rollback(value = false)
public void testAdd3(){//互相都添加
Customer c = new Customer();
c.setCustName("公信科技");
LinkMan linkMan = new LinkMan();
linkMan.setLkmName("肿瘤医院");
linkMan.setCustomer(c);
c.getLinkMans().add(linkMan);
//有一方放弃外建的维护
customerDao.save(c);
linkManDao.save(linkMan);
}
@Test
@Transactional
@Rollback(value = false)
public void testAdd4(){//级联添加
Customer c = new Customer();
c.setCustName("公信科技");
LinkMan linkMan = new LinkMan();
linkMan.setLkmName("肿瘤医院");
c.getLinkMans().add(linkMan);
//有一方放弃外建的维护
customerDao.save(c);
}
@Test
@Transactional
@Rollback(value = false)
public void testAdd5(){//级联删除与
Customer c = new Customer();
c.setCustName("公信科技");
c.setCustId(1L);
//有一方放弃外建的维护
customerDao.delete(c);
}
}
多对多查询
实体bean
@Entity
@Table(name = "sys_role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_id")
private Long roleId;
@Column(name = "role_name")
private String roleName;
//配置多对多
@ManyToMany(mappedBy = "roles") //配置多表关系 被动添加的一方放弃外键维护关系
private Set<User> users = new HashSet<>();
}
@Entity
@Table(name = "sys_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_id")
private Long userId;
@Column(name="user_name")
private String userName;
@Column(name="age")
private Integer age;
/**
* 配置用户到角色的多对多关系
* 配置多对多的映射关系
* 1.声明表关系的配置
* @ManyToMany(targetEntity = Role.class) //多对多
* targetEntity:代表对方的实体类字节码
* 2.配置中间表(包含两个外键)
* @JoinTable
* name : 中间表的名称
* joinColumns:配置当前对象在中间表的外键
* @JoinColumn的数组
* name:外键名
* referencedColumnName:参照的主表的主键名
* inverseJoinColumns:配置对方对象在中间表的外键
*/
@ManyToMany(targetEntity = Role.class,cascade = CascadeType.ALL)
@JoinTable(name = "sys_user_role",
//joinColumns,当前对象在中间表中的外键
joinColumns = {@JoinColumn(name = "sys_user_id",referencedColumnName = "user_id")},
//inverseJoinColumns,对方对象在中间表的外键
inverseJoinColumns = {@JoinColumn(name = "sys_role_id",referencedColumnName = "role_id")}
)
private Set<Role> roles = new HashSet<>();
}
dao层代码
只是简单的实现两个接口不做特殊说明
查询的代码
@RunWith(SpringRunner.class)
@SpringBootTest
public class ManyToManyTest {
@Autowired
private RoleDao roleDao;
@Autowired
private UserDao userDao;
@Test
@Transactional
@Rollback(false)
public void testAdd() {
User user = new User();
user.setUserName("小李");
Role role = new Role();
role.setRoleName("java程序员");
//配置用户到角色关系,可以对中间表中的数据进行维护 1-1
user.getRoles().add(role);
//配置角色到用户的关系,可以对中间表的数据进行维护 1-1
role.getUsers().add(user);
userDao.save(user);
roleDao.save(role);
}
@Test
@Transactional
@Rollback(false)
public void testCascadeAdd2() {
User user = new User();
user.setUserName("小李");
Role role = new Role();
role.setRoleName("java程序员");
//配置用户到角色关系,可以对中间表中的数据进行维护 1-1
user.getRoles().add(role);
userDao.save(user);
}
@Test
@Transactional
@Rollback(false)
public void testCascadeDelete() {
userDao.deleteById(1L);
}
}
对象查询
####查询对象
@RunWith(SpringRunner.class)
@SpringBootTest
public class ObjectQuery {
@Autowired
private CustomerDao customerDao;
@Autowired
private LinkManDao linkManDao;
@Test
@Transactional
@Rollback(value = false)
public void testQuery(){
Customer one = customerDao.getOne(1L);
Set<LinkMan> linkMans = one.getLinkMans();//延迟加载
for (LinkMan l:linkMans) {
System.out.println(l);
}
}
@Test
@Transactional
@Rollback(value = false)
public void testQuery2(){
LinkMan one = linkManDao.findById(1L).get();
Customer customer = one.getCustomer();
System.out.println(customer);
}
}