引入依赖 1 2 3 4 5 6 7 8 9 10 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-data-jpa</artifactId > </dependency > <dependency > <groupId > com.alibaba</groupId > <artifactId > druid</artifactId > <version > 1.2.8</version > </dependency >
application.yml 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 server: port: 80 servlet: context-path: / tomcat: uri-encoding: UTF-8 spring: application: name: microservice-student datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/db_bookmanagesystem?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456 jpa: hibernate: ddl-auto: update naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl show-sql: true
实体类 使用了lombok,如果不想使用就自行生成setter和getter方法
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 package com.ledao.entity;import lombok.Data;import javax.persistence.*;@Data @Entity @Table(name = "t_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "userName", length = 100) private String userName; @Column(name = "nickName", length = 100) private String nickName; @Column(length = 100) private String password; private Integer type; private Integer state; @Column(name = "isBorrow") private Integer isBorrow; }
Repository接口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 package com.ledao.repository;import com.ledao.entity.User;import org.springframework.data.jpa.repository.JpaRepository;public interface UserRepository extends JpaRepository <User , Long > {}
测试 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 27 28 package com.ledao;import com.ledao.entity.User;import com.ledao.repository.UserRepository;import org.junit.jupiter.api.Test;import org.springframework.boot.test.context.SpringBootTest;import javax.annotation.Resource;@SpringBootTest class BookManageSystemApplicationTests { @Resource private UserRepository userRepository; @Test void contextLoads () { User user = new User(); user.setUserName("admin" ); user.setNickName("乐道" ); user.setPassword("admin" ); user.setType(1 ); user.setState(1 ); user.setIsBorrow(1 ); userRepository.save(user); } }
结果 如果数据库的t_user表中新增了一条记录,说明引入Spring Data JPA成功