了解crudepository保存/更新

vzgqcmou  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(224)

我已经验证了我尝试更新的对象对于我尝试替换的条目有一个特定的id值,并且返回的对象是一个具有更高id值的新条目。我以为只要你提供了一个id值,它就会更新,而不是生成一个新的。我遗漏了一些注意事项吗?

System.out.println("!Parsed article ID = " + article.getID());
    Article returnedArticle = articleRepo.save(article);
    System.out.println("Saved article ID = " + returnedArticle.getID());

输出:

!Parsed article ID = 1
Saved article ID = 37

对象定义:

@Entity
abstract class DatabaseObject {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

…以及扩展项目实体中的其他字段
===更新时间:美国东部时间2月22日17:00===================================
我使用的是mysql,通过hibernate生成的查询是:

Hibernate: 
    select
        article0_.id as id2_0_0_,
        article0_.approved as approved3_0_0_,
        article0_.creators as creators4_0_0_,
        article0_.publish_date as publish_5_0_0_,
        article0_.title as title6_0_0_,
        article0_.text as text7_0_0_ 
    from
        database_object article0_ 
    where
        article0_.id=? 
        and article0_.dtype='Article'
Hibernate: 
    select
        next_val as id_val 
    from
        hibernate_sequence for update

Hibernate: 
    update
        hibernate_sequence 
    set
        next_val= ? 
    where
        next_val=?
Hibernate: 
    insert 
    into
        database_object
        (approved, creators, publish_date, title, text, dtype, id) 
    values
        (?, ?, ?, ?, ?, 'Article', ?)
ilmyapht

ilmyapht1#

这个答案有缺陷,或者提出了一个新问题。请阅读它知道我仍然会感谢一些帮助。
在阅读了大量关于 transient 、持久性和分离状态的内容后,我发现两个可操作的任务改善了这种情况:

Adding a    @Transactional tag to my method, and

Pulling up the old record from the database and modifying it, rather than trying to overwrite what may or may not be present in the database 

    @Transactional
    public ResponseEntity<Article> modifyArticle(@RequestHeader("client-key") UUID clientKey, @RequestBody JsonNode body) { //@RequestBody Article article) {

List<Article> articles = StreamSupport.stream(body.spliterator(), false)
        .map(ticketBody -> parseArticle(ticketBody))
        .collect(Collectors.toList());

        //There should only be one
        Article article = articles.get(0);

    Article returnedArticle;
        Optional<Article> maybeOldArticle = articleRepo.findById(article.getID());
        if (maybeOldArticle.isPresent()) {
            System.out.println("old article is present");
            Article oldArticle = maybeOldArticle.get();
            articleRepo.save(oldArticle);
            article.overwrite(oldArticle);
            returnedArticle = articleRepo.save(oldArticle);
        } else {
            System.out.println("old article is NOT present");
            returnedArticle = articleRepo.save(article);
        }

在上面的代码中,如果存在条目,我可以覆盖它。如果条目已被删除或什么都没有,它将创建一个新条目。这是不需要的。如何将空间用于数据库中不存在的条目?

相关问题