JPA是啥?一句话: 一种ORM规范。今天在这里不过多上干货,直接从最简单的角度带大家在Springboot 中实操JPA。
看了很多同学关于JPA博文,跟着跑一遍下来有实体类、service接口、实现类、控制类、映射接口的,从头到尾一堆代码,直接蒙圈。
JPA最简单用法在Repository (继承CurdRepository、PagingAndSortingRepository或JpaRepository或)的接口编写,建立数据库与实体间的映射。
最简单步骤:
- 建立一个springboot web项目(方法参考我的博文《Springboot入门篇-CSDN博客》)
- pom.xml中添加Jpa和数据库连接依赖
- application.properties中添加数据库配置和Jpa配置
- 数据库中添加一个测试表user
- 创建一个User实体类
- 创建一个UserRepository接口,建立数据库和实体User的映射(核心)
- 至此就可以操作数据库了
完成测试工程目录

Jpa和数据库连接依赖(版本自行根据实际情况匹配)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
application.properties中添加数据库配置和Jpa配置
#JDBC驱动 spring.datasource.driver-class-name=com.mysql.jdbc.Driver #数据库链接Url spring.datasource.url=jdbc:mysql://localhost:3306/test #数据库链接账号、密码 spring.datasource.username=root spring.datasource.password=123456 #每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新 spring.jpa.hibernate.ddl-auto=update #运行打印Sql(非必要) spring.jpa.show-sql=true
在test数据库中创建一个User数据表
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_unicode_ci ROW_FORMAT = Dynamic;
创建UserRepository接口
//public interface UserRepository extends CrudRepository<User, Integer> {
public interface UserRepository extends JpaRepository<User, Integer> {
/**
* 我们这里只需要写接口,不需要写实现,spring boot会帮忙自动实现
*
* */
@Query("from User where id =:id ")
public User getUser(@Param("id") Integer id);
}
注意这里主要是继承 CrudRepository或JpaRepository,两者区别和应用场景自行查资料。
通过继承把User实体和数据库映射起来。
至此就可以直接通过UserRepository的实例来操作数据了。
使用事例
创建一个Contorller
package com.nc.lengfeng04.controller;
import com.nc.lengfeng04.entity.User;
import com.nc.lengfeng04.service.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserRepository repository;
@RequestMapping("/getUser/{id}")
public User getUser(@PathVariable("id") Integer id){
return repository.getUser(id);//直接通过repository调用
}
}
操作结果


3259

被折叠的 条评论
为什么被折叠?



