Spring Boot 集成Spring Data JPA
环境:idea 2019 spring boot 版本 2.x
1:创建一个Spring Boot项目
勾选web模块中的spring web 和sql模块中的spring data jpa 和mysql驱动
2:在resources下创建application.yml文件
spring:
datasource:
#mysql 8.x版本连接方式
url: jdbc:mysql:///jpa?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Hongkong
username: root
password: 123
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
#更新或创建表结构
ddl-auto: update
#控制台显示sql
show-sql: true
配置完成,接下来我们写一个实体测试
@Entity//标注该类为一个实体
@Table(name = "t_user")//设置数据表名,可选,不些默认类名为表名 user
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //设置该字段在库中为自增主键
private Integer id;
//Column设置字段对应数据库的名字 可选 name不填默认为属性名 length为长度
@Column(name = "t_name",length = 25)
private String name;
@Column
private String email;
//此处setget方法省略....
/**
* 创建一个接口来完成对数据库的操作,里面不用写别的,继承的类中都有
* 需要继承JpaRepository类,该类封装了常用的方法 第一个参数传入实体,第二个参数传入主键类型
*/
public interface UserRepository extends JpaRepository<User,Integer> {
}
Controller
@RestController
public class Usercontroller {
//注入我们操作数据库的接口
@Autowired
private UserRepository repository;
//添加
@GetMapping("/save")
public User insertUser(User user){
User save = repository.save(user);
return user;
}
//根据ID删除
@GetMapping("/delete/{id}")
public void updateUser(@PathVariable("id") Integer id){
repository.deleteById(id);
}
//根据ID查询
@GetMapping("/user/{id}")
public Object getUser(@PathVariable("id") Integer id){
Optional<User> user = repository.findById(id);
System.out.println(user);
return user;
}
}
接下来开启启动类访问
http://localhost:8080/save?name=zhangsan&email=123456789
查询
删除,由于删除没有返回值,返回空白页面,查看数据库id为1的数据已经被删除了
本篇结束,有什么问题请各位指点,有不懂的也可以评论询问。