springboot+mysql语句
时间: 2023-12-01 10:42:34 浏览: 87
以下是使用SpringBoot和Spring Data JPA连接MySQL数据库并执行增删改查操作的示例代码:
1.在pom.xml文件中添加MySQL和Spring Data JPA依赖:
```xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
```
2.在application.properties文件中配置MySQL数据库连接信息:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
```
3.创建实体类User.java:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
// 省略getter和setter方法
}
```
4.创建Repository接口UserRepository.java:
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
}
```
5.创建Controller类UserController.java:
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("/add")
public User addUser(@RequestBody User user) {
return userRepository.save(user);
}
@GetMapping("/get/{id}")
public User getUser(@PathVariable Long id) {
return userRepository.findById(id).orElse(null);
}
@PutMapping("/update")
public User updateUser(@RequestBody User user) {
return userRepository.save(user);
}
@DeleteMapping("/delete/{id}")
public void deleteUser(@PathVariable Long id) {
userRepository.deleteById(id);
}
}
```
6.使用Postman等工具测试接口,例如添加用户:
请求方式:POST
请求URL:http://localhost:8080/user/add
请求参数:
```json
{
"username": "test", "password": "123456"
}
```
返回结果:
```json
{
"id": 1,
"username": "test",
"password": "123456"
}
```
阅读全文