spring-boot jpa

本文档详细介绍了如何在Spring Boot项目中使用JPA,包括依赖配置、实体类定义、Repository接口创建以及测试类的编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 dependency

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

2 实体类

import javax.persistence.*;

@Entity
@Table(name = "t_comment")
public class Comment {

    @Id //表明映射主键id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;  //评论id
    private String content; //评论内容
    private String author; //评论作者
    @Column(name = "a_id")
    private Integer aId; //外键:表示当前这条评论是属于那篇文章

    @Override
    public String toString() {
        return "Comment{" +
                "id=" + id +
                ", content='" + content + '\'' +
                ", author='" + author + '\'' +
                ", aId=" + aId +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Integer getaId() {
        return aId;
    }

    public void setaId(Integer aId) {
        this.aId = aId;
    }
}

3 repository

public interface CommentRepository extends JpaRepository<Comment,Integer> {
}

4 测试类

@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootDemoApplicationTests {
 //测试整合JPA
    @Autowired
    private CommentRepository commentRepository;

    @Test
    public void selectComment(){
        Optional<Comment> byId = commentRepository.findById(1);
        if(byId.isPresent()){}
        System.out.println(byId.get());
    }
    }
    ```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值