SpringBoot2.3.0配置JPA的实现示例
JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
依赖
- spring-boot-starter-data-jdbc
- spring-boot-starter-data-jpa
- mysql-connector-java
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</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>
application.yml
spring.jpa.hibernate.ddl-auto=update
- 如果数据库内没有表或表结构改变时根据Entity创建/更新
spring.jpa.show-sql=true
- 控制台打印sql
spring.jpa.database
- 指定数据库类型,可写可不写
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/spring_boot?serverTimezone=GMT%2B8 username: root password: root jpa: hibernate: ddl-auto: update show-sql: true database: mysql
POJO
- @Data是Lombok
- @Entity告诉JPA这是一个实体类(和数据表映射的类)
- @Table(name = “jpa_user”) 给表起名,不写默认为类名小写(user)
- @Id设置主键
- @GeneratedValue(strategy = GenerationType.IDENTITY) 使用自增
- @Column(name = “jpa_username”,length = 40) 给列起名,不写默认为属性名(username)
import lombok.Data; import javax.persistence.*; @Entity @Table(name = "jpa_user") @Data public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "jpa_username",length = 40) private String username; @Column(name = "jpa_password") private String password; }
Repository
JpaRepository的继承关系
所以继承JpaRepository
- JpaRepository<T, ID>
- 第一个泛型就是要操作的Entity
- 第二个泛型就是Entity的Id主键类型
- JpaRepository<User, Integer>
package com.live.repository; import com.live.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User,Integer> { }
Controller(测试)
@Autowired @Autowired UserRepository userRepository;
package com.live.controller; import com.live.model.User; import com.live.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.Optional; @RestController public class UserJPAController { @Autowired UserRepository userRepository; @GetMapping("/findAll") public List<User> findAll() { return userRepository.findAll(); } @GetMapping("/findOne/{id}") public Optional<User> findOne(@PathVariable(value = "id") Integer id) { return userRepository.findById(id); } @GetMapping("/insert") public User insertOne(User user) { return userRepository.save(user); } }
测试
注意:
- 对字段操作时,使用的是实体类的属性名(username,password)
- 而不是在@Column(name=“jpa_username”)设置的jpa_username
查询所有
插入
到此这篇关于SpringBoot2.3.0配置JPA的实现示例的文章就介绍到这了,更多相关SpringBoot2.3.0配置JPA内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)