C
C
Crunchor2019-12-08 21:37:07
Java
Crunchor, 2019-12-08 21:37:07

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;
}

Book table
@Entity
@Getter
@Setter
public class Book implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
...

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Author author;
}

All entities are created using JAXB from an XMl file. Everything is fine, except that the book object has a null author field.
Database entry code:
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.persist(author);
session.getTransaction().commit();
session.close();

In this case, rows are written to the book and author tables, only book.author_id = null.
When executing the code
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
author.getBook().setAuthor(author);
session.persist(author);
session.getTransaction().commit();
session.close();

All data is recorded as I need.
The problem is that there are a lot of such tables and relationships, and writing commands like author.getBook().setAuthor(author) is not correct in my opinion. And the team itself looks a bit strange.
How to force hibernate to automatically substitute a reference to the parent in child elements?
ps Instead of @MapsId, I wrote @JoinColumn, but this did not affect the result.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
C
Crunkor, 2020-01-09
@Crunkor

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;
    }

After that everything started working.

S
Sergey Litvinov, 2019-12-28
@SeApps

Either I'm dumb or CascadeType.ALL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question