springboot根据ID更新数据
时间: 2023-10-12 13:18:36 浏览: 40
在Spring Boot中,可以使用JPA(Java Persistence API)或者MyBatis等ORM框架来更新数据。
下面以JPA为例,演示根据ID更新数据的方法。
1. 定义实体类
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// getter/setter省略
}
```
2. 定义Repository接口
```java
public interface UserRepository extends JpaRepository<User, Long> {
}
```
3. 编写更新方法
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User updateUserById(Long id, User user) {
Optional<User> optional = userRepository.findById(id);
if (optional.isPresent()) {
User existUser = optional.get();
existUser.setUsername(user.getUsername());
existUser.setPassword(user.getPassword());
return userRepository.save(existUser);
}
return null;
}
}
```
在更新方法中,首先通过id查询出要更新的数据,然后将传入的user对象的数据更新到查询出的数据中,最后调用JpaRepository的save方法保存更新后的数据。
4. 测试更新方法
```java
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testUpdateUserById() {
User user = new User();
user.setUsername("test");
user.setPassword("123456");
User savedUser = userService.saveUser(user); // 先保存一个用户
User updateUser = new User();
updateUser.setUsername("update");
updateUser.setPassword("update123");
User updatedUser = userService.updateUserById(savedUser.getId(), updateUser); // 更新用户数据
Assert.assertEquals("update", updatedUser.getUsername()); // 断言更新后的用户名为"update"
Assert.assertEquals("update123", updatedUser.getPassword()); // 断言更新后的密码为"update123"
}
}
```
在测试方法中,先保存一个用户数据,然后通过更新方法更新该用户的数据,并断言更新后的数据是否正确。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)