SpringBoot学习笔记(⼗)Spring Boot整合JPA
使⽤Spring Boot整合JPA
1. 编写ORM实体类:实体类与数据表进⾏映射,并且配置好映射关系。
⾸先先创建⼀个实体类,命名为Discuss
package com.itheima.chapter03.domain;
public class Discuss {
}
在编写属性之前,这个实体类要对应的表有多少个字段,如下图可知有四个字段。
所以对应的,在这个实体类中,也应该有四个字段。
package com.itheima.chapter03.domain;
public class Discuss {
private Integer id;
private String content;
private String author;
private Integer aId;
//省略get/set/tostring
}
添加注解,建⽴实体类与表的映射关系
@Entity(name ="t_comment")//该注解表⽰当前实体类是与表有映射关系的实体类
@Id//该注解表⽰配置该属性对应的字段为主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//表⽰当前主键⽣成策略为⾃增长
@Column(name ="")//配置当前属性与字段的映射关系
完整代码如下:
import javax.persistence.*;
@Entity(name ="t_comment")//该注解表⽰当前实体类是与表有映射关系的实体类
public class Discuss {
@Id//该注解表⽰配置该属性对应的字段为主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//表⽰当前主键⽣成策略为⾃增长
private Integer id;
@Column(name ="content")//配置当前属性与字段的映射关系
private String content;
@Column(name ="author")
private String author;
@Column(name ="aId")
private Integer aId;
//省略get/set/tostring
}
2. 编写Repository接⼝:针对不同的表数据操作编写各⾃对应的Repository接⼝,并根据需要编写对应的数据操作⽅法。在项⽬包下创建⼀个respoitory包,在该包下创建⼀个DiscussRepository接⼝,编写如下代码:
public interface DiscussRepository extends JpaRepository<Discuss,Integer>{
//1.查询author⾮空的Discuss评论集合
public List<Discuss>findByAuthorNotNull();
//2.根据⽂章id分页查询Discuss评论集合
@Query("SELECT c from t_comment c where aId = ?1")
public List<Discuss>getDiscussPaged(Integer aId, Pageable pageable);
//3.使⽤元素SQL语句,根据⽂章id分页查询Discuss评论集合
@Query(value ="SELECT * from t_comment where a_Id =?1",nativeQuery =true)
public List<Discuss>getDiscussPaged2(Integer aid,Pageable pageable);
//4.根据评论id修改评论作者author
@Transactional
@Modifying
@Query("UPDATE t_comment c set c.author = ?1 where id=?2")
public int updateDiscuss(String author,Integer id);
//5.根据评论id删除评论
@Transactional
适合新手的spring boot
@Modifying
@Query("delete from t_comment where id=?1")
public int deleteDiscuss(Integer id);
}
在项⽬测试包下新建⼀个测试⽅法JpaTests,编写如下代码:
@SpringBootTest
public class JpaTests {
@Autowired
private DiscussRepository discussRepository;
@Test
public void test1(){
Optional<Discuss> byId = discussRepository.findById(1);
System.out.());
}
}
运⾏得到输出结果: