springboot -- JPA简单运用
程序员文章站
2022-04-21 12:05:17
...
1、导入相关依赖
<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>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
<scope>runtime</scope>
</dependency>
2、配置文件(application.yml)
spring:
datasource:
url: jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: admin
jpa:
hibernate:
ddl-auto: update
show-sql: true
3、创建实体类
package com.example.bean;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="_user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String lastName;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
4、创建实现JPA的接口
package com.example.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.bean.User;
public interface UserResposity extends JpaRepository<User, Integer>{
}
5、调用测试
package com.example.controller;
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 com.example.bean.User;
import com.example.dao.UserResposity;
@RestController
public class UserController {
@Autowired
UserResposity userResposity;
@GetMapping("/user/{id}")
public User get(@PathVariable("id") int id){
return userResposity.findOne(id);
}
@GetMapping("/user")
public User add(User user){
return userResposity.saveAndFlush(user);
}
}
推荐阅读
-
简单jqueryd的运用之仿邮件代码实现
-
关于js对象的简单运用
-
iOS应用设计模式开发中对简单工厂和工厂方法模式的运用
-
vue(2)—— vue简单语法运用,常用指令集
-
vuejs2.0运用原生js实现简单的拖拽元素功能示例
-
简单了解springboot加载配置文件顺序
-
SpringBoot使用AOP+注解实现简单的权限验证的方法
-
javaweb各种框架组合案例(六):springboot+spring data jpa(hibernate)+restful
-
SpringBoot+Dubbo+Zookeeper整合搭建简单的分布式应用
-
springboot+mybatis日志显示SQL的最简单方法