当前位置: 代码迷 >> 综合 >> SpringData JPA
  详细解决方案

SpringData JPA

热度:98   发布时间:2023-12-11 23:17:24.0

一、基本介绍   

Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问技术,包括非关系数据库、 Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。

? Spring Data 包含多个子项目:

二、整合SpringData JPA

1、pom.xml文件

<properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

2、全局配置文集application.yml

spring:datasource:url: jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=UTCusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driverjpa:hibernate:#更新或者创建数据表结构ddl-auto: update#控制台显示SQLshow-sql: true

3、实体类User.java

//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是user;
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})
public class User {@Id //这是一个主键@GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键private Integer id;@Column(name = "last_name",length = 50) //这是和数据表对应的一个列private String lastName;@Column //省略默认列名就是属性名private String email;
}

4、UserRepository.java

//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository<User,Integer> {
}

5、UserController.java

@RestController
public class UserController {@Autowiredprivate UserRepository userRepository;@GetMapping("/user/{id}")public User getUser(@PathVariable("id") Integer id){User user = userRepository.getOne(id);return user;}@GetMapping("/user")public User insertUser(User user){User save = userRepository.save(user);return save;}
}

6、访问:http://localhost:8080/user/1

访问:http://localhost:8080/user?lastName=zhangsan&email=123@qq.com