SpringBoot 与 JPA
Posted lwhzwb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot 与 JPA相关的知识,希望对你有一定的参考价值。
1.导入依赖
<!-- 引入mysql需要的依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 引入spring data jpa需要的依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
2. 创建src/main/resource下的application.yml文件
##数据库四大连接参数 spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql:///springbootjpa username: root password: 123 ##jpa表的生成策略 jpa: hibernate: ddl-auto: update
3.创建Grade实体类
@Entity public class Grade { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Integer grade_id; private String grade_name; public Integer getGrade_id() { return grade_id; } public void setGrade_id(Integer grade_id) { this.grade_id = grade_id; } public String getGrade_name() { return grade_name; } public void setGrade_name(String grade_name) { this.grade_name = grade_name; } }
4. 创建dao层
/** * CrudRepository<实体,主键数据类型> */ @Repository public interface IGradeMapper extends CrudRepository<Grade,Integer> { }
5. 创建service层接口
public interface IGradeService { public Grade insertGrade(Grade grade); public Grade updateGrade(Grade grade); public void deleteGrade(Integer id); public Iterable<Grade> getAll(); }
6.创建service实现类
@Service("iGradeService") public class IGradeServcieImpl implements IGradeService { @Resource private IGradeMapper iGradeMapper; @Override public Grade insertGrade(Grade grade) { return iGradeMapper.save(grade); } @Override public Grade updateGrade(Grade grade) { return iGradeMapper.save(grade); } @Override public void deleteGrade(Integer id) { iGradeMapper.delete(id); } @Override public Iterable<Grade> getAll() { return iGradeMapper.findAll(); } }
7. 创建controller层
@RestController @RequestMapping("/IGradeController") public class IGradeController { @Resource private IGradeService iGradeService; //新增数据 @RequestMapping("/insertGrade") public Grade insertGrade(){ Grade grade=new Grade(); grade.setGrade_name("S1"); return iGradeService.insertGrade(grade); } @RequestMapping("/updateGrade") public Grade updateGrade(){ Grade grade=new Grade(); grade.setGrade_id(1); grade.setGrade_name("S2"); return iGradeService.updateGrade(grade); } @RequestMapping("/deleteGrade") public void deleteGrade(){ iGradeService.deleteGrade(1); } @RequestMapping("/getAllGrade") public Iterable<Grade> getAllGrade(){ return iGradeService.getAll(); } }
8.创建StartSpringBoot测试类
@SpringBootApplication public class StartSpringBoot { public static void main(String[] args) { SpringApplication.run(StartSpringBoot.class,args); } }
9.浏览器测试
(1.)基本理论
JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
以上是关于SpringBoot 与 JPA的主要内容,如果未能解决你的问题,请参考以下文章