标签:持久 aik save 持久层框架 最大的 amp 过程 就会 sdfs
<!--springdatajpa依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.1.3.RELEASE</version> </dependency> <!--mysql 依賴--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
server.port=8081 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver #配置自动建表 spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
public interface StudentRepository extends JpaRepository<Student,Integer> { }
Student.java的代码。@Entitry表示该类是实体类,@Table在MySQL创建的表名,项目一启动就会自动创建,@Data需要引入lombok,这里我是为了方便,可以不用写get/set方法。
@Data @Entity @Table(name = "tb_student") @Component public class Student { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id ; @Column(name = "name",length = 50) private String name; @Column(name = "email",length = 100) private String email; }
controller层代码,我是跳过了业务层直接跳持久层了,当然实际开发是不会这样的。
@RestController public class StudentController { @Autowired StudentRepository studentRepository; @Autowired Student student; @RequestMapping("/getAll") public List<Student> queryStudent(){ List<Student> list = new ArrayList<>(); list = studentRepository.findAll(); return list ; } @RequestMapping("/getByID") public Optional<Student> queryStudentbyid() { List<Student> list = new ArrayList<>(); Optional<Student> student= studentRepository.findById(1); return student; } @RequestMapping("/add") public Student addStudent(){ student.setId(121111); student.setEmail("wewsdsdfs"); student = studentRepository.save(student); return student; } }
在浏览器访问的结果
"id":1,"name":"qinda","email":"1214111520@qq.com"},{"id":2,"name":"haha","email":"121"},{"id":3,"name":null,"email":"wewsdsdfs"}]
Springboot整合SpringDataJpa入门篇(一)
标签:持久 aik save 持久层框架 最大的 amp 过程 就会 sdfs
原文地址:https://www.cnblogs.com/qinda/p/10965178.html