Answer the question
In order to leave comments, you need to log in
How to force Hibernate to automatically bind objects?
Good afternoon
There are tables:
Table Author
@Entity
@Getter
@Setter
public class Author implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
....
@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY, mappedBy = "author")
private Book book;
}
@Entity
@Getter
@Setter
public class Book implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
...
@OneToOne(fetch = FetchType.LAZY)
@MapsId
private Author author;
}
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.persist(author);
session.getTransaction().commit();
session.close();
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
author.getBook().setAuthor(author);
session.persist(author);
session.getTransaction().commit();
session.close();
Answer the question
In order to leave comments, you need to log in
Problem solved.
Everything turned out to be quite simple.
Because the object was created using JAXB, then during the formation it was necessary to indicate to it a reference to the parent object
void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
author = (Author ) parent;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question