
2)、整合SpringData JPA JPA:ORM(Object Relational Mapping);
yml文件配置
spring:
datasource:
username: ecc_event_management
password: 999999
url: jdbc:mysql://100.0.0.8:3306/test
driver‐class‐name: com.mysql.jdbc.Driver
#type: com.alibaba.druid.pool.DruidDataSource
jpa:
hibernate:
ddl-auto: update #更新或创建
show-sql: true #控制台显示
1)、编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
bean:
package com.ecc.springbootjpa.bean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import javax.persistence.*;
/**
* @author sunyc
* @create 2022-04-27 9:08
*/
/*
使用jpa注解,配置映射关系
*/
@Entity /*告诉jpa这是一个实体类和数据表映射*/
@Table(name="user_temp") /*@table来指定和那个数据表对应,如果省略默认表为 user_temp*/
public class User {
@Id//这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增逐渐
private int id;
@Column //这是和数据集对应的一个列 省略默列名就是属性名
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2)、编写一个Dao接口来操作实体类对应的数据表(Repository)
public interface Userrepository extends JpaRepository<User,Integer> {
}
yml文件配置
spring:
datasource:
username: ecc_event_management
password: 999999
url: jdbc:mysql://100.0.0.8:3306/test
driver‐class‐name: com.mysql.jdbc.Driver
#type: com.alibaba.druid.pool.DruidDataSource
jpa:
hibernate:
ddl-auto: update #更新或创建
show-sql: true #控制台显示
运行环境,这个时候就在数据库建表完成了:

登陆数据库验证:

控制层:
package com.ecc.springbootjpa.controller;
import com.ecc.springbootjpa.bean.User;
import com.ecc.springbootjpa.repository.Userrepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
/**
* @author sunyc
* @create 2022-04-27 9:23
*/
@RestController
public class UserController {
@Autowired
Userrepository userrepository;
//根据ID查询
@GetMapping("user/{id}")
public User getUser(@PathVariable("id") Integer id){
return userrepository.getById(id);
}
//insert
@GetMapping("/user")
public User insertUser(User user){
User save = userrepository.save(user);
return save;
}
}
1454

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



