SpringBoot+Spring Data JPA
1. 添加起步依赖
1 2 3 4 5 | <!-- spring data jpa起步依赖 --> < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-jpa</ artifactId > </ dependency > |
2.配置文件
配置项参考 SpringBoot+JPA初始化数据库表
1 2 3 | spring.jpa.hibernate.ddl-auto=update #spring.jpa.show-sql= true #spring.jpa.generate-ddl= true |
3. 建实体类 运行项目 就会在数据库中自动建表t_student
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table (name = "t_student" ) public class Student { @Id @GeneratedValue (strategy = GenerationType.AUTO) private Long id; @Column private String name; @Column private String homeAddress; private Long homeTel; } |
4.建repository
1 2 3 4 5 6 7 8 9 | import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.stereotype.Repository; @Repository public interface StudentRepository extends JpaRepository<Student, Long>,JpaSpecificationExecutor<Student> { } |
5.建service
1 2 3 4 5 | public interface StudentService { Student save(Student student); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepository; @Override public Student save(Student student) { return studentRepository.save(student); } } |
6.建controller 运行项目,调用方法saveStudent就可以实现 持久化student对象到数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RequestMapping ( "/api" ) @RestController public class StudentController { @Autowired private StudentService studentService; @PostMapping ( "/students" ) @ResponseBody public String saveStudent( @RequestBody Student student) { Student savestudent = studentService.save(student); return savestudent.getName(); } } |
分类:
Spring Boot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端