Reputation: 105
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'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 = "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<>();
}
and the author class
@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<>();
}```
Upvotes: 0
Views: 44
Reputation: 706
please begin your transaction and not only get the transaction: replace the
entityManager.getTransaction();
by
entityManager.getTransaction().begin();
Upvotes: 1