Hibernate分离实体,我相信。

huangapple go评论55阅读模式
英文:

Hibernate detached entity i believe

问题

我在处理 Hibernate 方面时有点初学者但我已经花了几个小时来解决一个问题现在需要你的帮助

我有一个管理文章的应用程序每篇文章都是由某位作者编写的
我想要做的是将一篇文章添加到数据库中其中的 author_id 字段为空然后仅在此之后再更新该字段
然而Hibernate 拒绝在数据库中更新我的实体
```java
public <Article> void updateElement(Article entity) {
    EntityManager entityManager = createEntityManager();
    try {
        entityManager.getTransaction();
        entityManager.merge(entity);
        entityManager.getTransaction().commit();
    }
    catch(RuntimeException e ){
        entityManager.getTransaction().rollback();
    }
    finally {
        entityManager.close();
    }
}

这是我尝试更新条目的方式。我会收到一篇文章作为参数,我确定它肯定在数据库中。然后我尝试执行合并操作以进行更新。但我不知道这是否是正确的方法。请帮助我。

文章类:

@ToString
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@Entity
@Table(name = "Article")
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "article_id")
    private Integer id;

    @NotBlank
    @Column(name = "title")
    private String title;

    @NotBlank
    @Column(name = "publication_date")
    private Date publicationDate;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "author_id")
    private Author author;

    @ManyToMany(fetch = FetchType.EAGER)
    @Enumerated(EnumType.STRING)
    @JoinTable(name = "article_tags",
                joinColumns = @JoinColumn(name = "article_id"),
                inverseJoinColumns = @JoinColumn(name = "tag_id"))
    private Set<Tag> tags = new HashSet<>();
}

以及作者类:

@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@Entity
@Table(name = "Authors")
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator = "entity_id_seq")
    @Column(name = "author_id", updatable = false)
    private int id;

    @NotBlank
    @Column(name = "author_name")
    private String name;

    @OneToMany(mappedBy = "author", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Article> writtenArticles = new HashSet<>();
}


<details>
<summary>英文:</summary>

I am kinda beginner when it comes to hibernate, but i have been dealing with a problem for several hours, and i need your help.

I have an application that manages articles, and each article is written by an author. 
What i want to do is to add an article to a database, with its author_id field being null, and only after that to update that field.
However, hibernate refuses to update my entity in the database.

public <Article> void updateElement(Article entity) {
EntityManager entityManager = createEntityManager();
try {
entityManager.getTransaction();
entityManager.merge(entity);
entityManager.getTransaction().commit();
}
catch(RuntimeException e ){
entityManager.getTransaction().rollback();
}
finally {
entityManager.close();
}
}


This is how i try to update the entry. I receive an Article as a parameter, for which i know for sure that it is in the database. And after that i try to do merge in order to update it. But i don&#39;t know if it the right approach. Please help me.

The article class:

@ToString
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@Entity
@Table( name = "Article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "article_id")
private Integer id;

@NotBlank
@Column(name = &quot;title&quot;)
private String title;

@NotBlank
@Column(name = &quot;publication_date&quot;)
private Date publicationDate;

@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name = &quot;author_id&quot;)
private Author author;

@ManyToMany(fetch = FetchType.EAGER)
@Enumerated(EnumType.STRING)
@JoinTable(name = &quot;article_tags&quot;,
            joinColumns = @JoinColumn(name = &quot;article_id&quot;),
            inverseJoinColumns = @JoinColumn(name =&quot;tag_id&quot;))
private Set&lt;Tag&gt; tags = new HashSet&lt;&gt;();

}

and the author class
```@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
@Entity
@Table(name = &quot;Authors&quot;)
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE,
            generator = &quot;entity_id_seq&quot;)
    @Column(name = &quot;author_id&quot;,updatable = false)
    private int id;

    @NotBlank
    @Column(name = &quot;author_name&quot;)
    private String name;

    @OneToMany(mappedBy = &quot;author&quot;,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    private Set&lt;Article&gt; writtenArticles = new HashSet&lt;&gt;();

}```

</details>


# 答案1
**得分**: 1

请开始您的事务,不仅获取事务:
将

            entityManager.getTransaction();
替换为

            entityManager.getTransaction().begin();

<details>
<summary>英文:</summary>

please begin your transaction and not only get the transaction:
replace the

            entityManager.getTransaction();
by

            entityManager.getTransaction().begin();


</details>



huangapple
  • 本文由 发表于 2020年7月26日 05:03:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63093553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定