gpt4 book ai didi

java - Spring Boot MVC 中如何更新数据

转载 作者:行者123 更新时间:2023-12-02 05:52:03 25 4
gpt4 key购买 nike

我有一个关于 Spring Boot MVC 的最常见的项目。我正在尝试通过 PUT 写入更新数据。

@RestController
@RequestMapping(CommentController.PATH)
public class CommentController {

public final static String PATH = "/comments";

@Autowired
private CommentService service;

@PutMapping("/{id}")
public Comment update(@RequestBody Comment comment, @PathVariable Long id) {
return service.update(id, comment);
}
}

@Service
public class CommentService {

@Autowired
private CommentRepository repository;

public Comment update(Long id, Comment entity) {
Optional<Comment> optionalEntityFromDB = repository.findById(id);
return optionalEntityFromDB
.map(e -> saveAndReturnSavedEntity(entity, e))
.orElseThrow(getNotFoundExceptionSupplier("Cannot update - not exist entity by id: " + id, OBJECT_NOT_FOUND));
}

private Comment saveAndReturnSavedEntity(Comment entity, Comment entityFromDB) {
entity.setId(entityFromDB.getId());
return repository.save(entity);
}

}

@Repository
public interface CommentRepository extends JpaRepository<Comment, Long> {
}

@Entity
public class Comment {
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;

@Column(name = "name")
protected String name;
}

然后我编写一个能够检查更新数据的测试:

@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
// DBUnit config:
@DatabaseSetup("/comment.xml")
@TestExecutionListeners({
TransactionalTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
public class CommentControllerTest {

private MockMvc mockMvc;
private static String route = PATH + "/{id}";

@Autowired
private CommentController commentController;

@Autowired
private CommentRepository commentRepository;

@PersistenceContext
private EntityManager entityManager;

@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(commentController)
.build();
}

@Test
public void update_ShouldReturnCreated2() throws Exception {
int id = 1;
String name = "JohnNew";
Comment expectedComment = new Comment();
expectedComment.setName(name);

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(expectedComment);

this.mockMvc.perform(put(route, id)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.content(json))
.andDo(print());

entityManager.clear();
entityManager.flush();

Comment commentUpdated = commentRepository.findById(1L).get();
assertThat(commentUpdated.getName(), equalTo(name)); // not equals!
}
}

评论.xml:

<dataset>
<Comment id="1" name="John" />
</dataset>

但是问题是数据没有更新。如果启用 Hibernat 的日志记录,则也不会向数据库发出更新请求。我做错了什么?

最佳答案

您缺少 CommentService 中的 @Transactional 注释。虽然最好将其添加到每个方法级别,但请尝试将其添加到类级别以验证是否可以修复问题:

@Service
@Transactional
public class CommentService {

关于java - Spring Boot MVC 中如何更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56040887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com