springboot集成mysql
时间: 2023-10-13 22:27:55 浏览: 91
Spring Boot是一个快速开发框架,可以轻松集成MySQL数据库。下面是Spring Boot集成MySQL的步骤:
1. 添加MySQL依赖
在pom.xml文件中添加MySQL的依赖:
```
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
```
2. 配置MySQL连接
在application.properties文件中添加MySQL连接的配置:
```
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 创建实体类
创建一个实体类,用于映射数据库表:
```
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private Integer age;
// 省略getter和setter方法
}
```
4. 创建Repository
创建一个Repository接口,用于定义对数据库的操作:
```
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
5. 编写业务逻辑
编写业务逻辑代码,使用Repository进行数据的增删改查操作:
```
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
public User addUser(User user) {
return userRepository.save(user);
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
public User updateUser(User user) {
return userRepository.save(user);
}
}
```
6. 测试
编写测试代码,测试业务逻辑的正确性:
```
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
@Test
void testAddUser() {
User user = new User();
user.setName("张三");
user.setAge(20);
User newUser = userService.addUser(user);
assertNotNull(newUser.getId());
}
@Test
void testGetUserById() {
User user = new User();
user.setName("张三");
user.setAge(20);
User newUser = userService.addUser(user);
User getUser = userService.getUserById(newUser.getId());
assertEquals("张三", getUser.getName());
}
@Test
void testGetAllUsers() {
List<User> userList = userService.getAllUsers();
assertEquals(1, userList.size());
}
@Test
void testUpdateUser() {
User user = new User();
user.setName("张三");
user.setAge(20);
User newUser = userService.addUser(user);
newUser.setName("李四");
User updateUser = userService.updateUser(newUser);
assertEquals("李四", updateUser.getName());
}
@Test
void testDeleteUser() {
User user = new User();
user.setName("张三");
user.setAge(20);
User newUser = userService.addUser(user);
userService.deleteUser(newUser.getId());
User deleteUser = userService.getUserById(newUser.getId());
assertNull(deleteUser);
}
}
```
以上就是Spring Boot集成MySQL的全部步骤。
阅读全文