本文已参与「新人创作礼」活动,一起开启掘金创作之路。
文章目录
SpringBootJpa简单操作Mysql数据库
pom文件依赖
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
properties文件配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
##JPA配置
## validate 加载hibernate时,验证创建数据表结构
## create 每次加载hibernate,重新创建数据表结构,这会导致数据表数据丢失
## create-drop 加载hibernate时创建,退出时删除表结构
## update 加载hibernate自动更新数据库结构
## none 启动时不做任何操作
spring.jpa.hibernate.ddl-auto=create
## 控制台打印
spring.jpa.show-sql=true
User实体类
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String user_name;
@Column
private String user_password;
public User(Long id, String user_name, String user_password){
this.id = id;
this.user_name = user_name;
this.user_password = user_password;
}
public User(String user_name, String user_password){
this.user_name = user_name;
this.user_password = user_password;
}
public User(){
};
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
}
UserRepository类,继承JpaRepository类,具有简单的操作数据库函数
public interface UserRepository extends JpaRepository<User, Long> {
}
创建UserCOntroller,并注入UserRepository
@RestController
@RequestMapping("test")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/saveUser")
public void saveUser(String userName, String userPassword){
User user = new User(userName, userPassword);
userRepository.save(user);
}
@GetMapping("/updateUser")
public void updateUser(Long id, String userName, String userPassword){
User user = new User(id, userName, userPassword);
userRepository.save(user);
}
@GetMapping("/deleteUser")
public void deleteUser(Long id){
userRepository.deleteById(id);
}
@GetMapping("/getUserById")
public Optional<User> getUserById(Long id){
return userRepository.findById(id);
}
}