1.pom依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency>
2.entity class
package cn.likui.study.studyjpa.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; /** * @Description: * @Author: ldg * @Date: 2020/10/10 */ @Builder @NoArgsConstructor @AllArgsConstructor @Data @Entity @Table(name="tb_study_jpa") public class StudyJpa { /** * 主键自增 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name ="name",length = 50) private String name; @Column(length = 50) private String phone; }
3.dao层
package cn.likui.study.studyjpa.dao; import cn.likui.study.studyjpa.entity.StudyJpa; import org.springframework.data.jpa.repository.JpaRepository; /** * @Description: * @Author: ldg * @Date: 2020/10/10 */ public interface StudyJpaRepository extends JpaRepository<StudyJpa,Integer> { }
4.controller
package cn.likui.study.studyjpa.controller; import cn.likui.study.studyjpa.dao.StudyJpaRepository; import cn.likui.study.studyjpa.entity.StudyJpa; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * @Description: 直接操作 Repository * @Author: ldg * @Date: 2020/10/10 */ @RestController @RequestMapping("/jpa") public class StudyJpaController { @Autowired private StudyJpaRepository studyJpaRepository; @PostMapping("/findAll") public List<StudyJpa> update() { List<StudyJpa> all = studyJpaRepository.findAll(); return all; } @PostMapping("/save") public StudyJpa save() { StudyJpa studyJpa = StudyJpa.builder().name("张三").phone("010-88888888").build(); StudyJpa save = studyJpaRepository.save(studyJpa); return save; } }
5.yml配置
server: port: 8889 spring: datasource: url: jdbc:mysql://localhost:3306/likui?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: #更新或创建数据库表结构 ddl-auto: update #输出执行sql show-sql: true