SpringBoot之整合JPA

2022-07-04 09:29:24

Spring Boot整合JPA

1、在pom文件中添加Spring Data JPA依赖启动器

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifacId>spring-boot-starter-data-jpa</artifactId>
 </dependency>

2、编写ORM实体类

//该实体类要与mysql数据库里的表进行映射配置(假设为t_comment表)

@Entity(name="t_comment")         //该注解表示该表是一个与表有映射关系的实体类
public class Discuss{
    @Id     //表示该属性映射的字段为主键字段
    @GeneratedVlue(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接口

针对不同的表数据操作编写各自对应的Repositor接口,并根据需要编写对应的数据操作方法。

public interface DiscussRepository extends JpaRepository<Discuss, Integer>
{
    //查询author非空的Discuss评论集合
    public List<Discuss> FindByAuthorNotNull();

    //根据文章id分页查询Discuss评论集合
    //通过“@Query”注解来执行这条SQL语句,"?"代表将第一个参数赋值给占位符“1”
    @Query("SELECT c FROM t_comment c WHERE c.aId = ?1") 
    public List<Discuss> getDiscussPaged(Integer aid, Pageable pageable);

    //使用元素SQL语句,根据文章id分页查询Discuss评论集合
    //nativeQuery = true表示写的是SQL语句
    @Query(value="SELECT * FROM t_comment WHERE n_Id = ?1", nativeQuery = true)
    public List<Discuss> getDiscussPaged(Integer aid, Pageable pageable);

    //根据评论id修改评论作者author
    @Transactional  //进行事务控制
    @Modifying  //如果对数据库做出了一些操作,就要添加这个注解
    @Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2")
    public int updateDiscuss(String author,Integer id);

    //根据评论id删除评论
    @Transactional
    @Modifying
    @Query("DELETE FROM t_comment c WHERE c.id = ?1")
    public int deleteDiscuss(Integer id);
       
}

3 编写测试类

//测试crudRepository中提供的简单的增删改查方法
@Test    
public void test1()
{
    Optional<Discuss> byId = discussRepository.findById(1);
    System.out.println(byId.get());
}
//测试findByAuthorNotNull 方法
@Test
public void test2()
{
    List<Discuss> byAuthorNotNull = discussRepository.findByAuthorNotNull();
    for(Discuss discuss : byAuthorNotNull)
    {
        System.out.println(discuss);
    }
}
//测试删除
@Test
public void test3()
{
   int i = discussRepository.deleteDiscuss(5);
   System.out.println(i);
}
  • 作者:熊凯瑞
  • 原文链接:https://blog.csdn.net/qq_46106857/article/details/123918340
    更新时间:2022-07-04 09:29:24