springboot配置mysql数据源并使用EntityManager查询
时间: 2024-01-06 07:07:12 浏览: 83
Spring配置MySQL数据源
好的,下面是一个简单的使用Spring Boot配置MySQL数据源并使用EntityManager进行查询的示例:
1. 在pom.xml文件中添加mysql-connector-java依赖:
```xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
```
2. 在application.yml文件中配置数据源信息:
```yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
```
3. 创建一个实体类User.java:
```java
import javax.persistence.*;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
// 省略getter和setter方法
}
```
4. 创建一个数据访问类UserDao.java:
```java
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
@Repository
public class UserDao {
@PersistenceContext
private EntityManager entityManager;
public User getUserById(Long id) {
return entityManager.find(User.class, id);
}
public List<User> getAllUsers() {
String hql = "from User";
return entityManager.createQuery(hql, User.class).getResultList();
}
public void addUser(User user) {
entityManager.persist(user);
}
public void updateUser(User user) {
entityManager.merge(user);
}
public void deleteUserById(Long id) {
User user = entityManager.find(User.class, id);
entityManager.remove(user);
}
}
```
5. 创建一个控制器UserController.java:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserDao userDao;
@GetMapping("/{id}")
public User getUserById(@PathVariable Long id) {
return userDao.getUserById(id);
}
@GetMapping("/all")
public List<User> getAllUsers() {
return userDao.getAllUsers();
}
@PostMapping("/")
public String addUser(@RequestBody User user) {
userDao.addUser(user);
return "success";
}
@PutMapping("/")
public String updateUser(@RequestBody User user) {
userDao.updateUser(user);
return "success";
}
@DeleteMapping("/{id}")
public String deleteUserById(@PathVariable Long id) {
userDao.deleteUserById(id);
return "success";
}
}
```
至此,我们已经完成了Spring Boot配置MySQL数据源并使用EntityManager进行查询的示例。在这个示例中,我们使用了@Entity、@Table、@Id、@GeneratedValue、@Column、@PersistenceContext、@Repository、@RestController、@RequestMapping、@GetMapping、@PostMapping、@PutMapping和@DeleteMapping等注解,这些注解都是Spring Boot框架中常用的注解,用于简化开发流程,提高开发效率。
阅读全文