Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate - synchronize two properties mapping the same column

Is it possible to keep sync two properties on the same entity mapped to the same column (with basic JPA, or with hibernate)?

I have two properties:

@JoinColumn(referencedColumnName = "id", insertable = false, name = "parent", updatable = false)
@ManyToOne(fetch = FetchType.LAZY)
private Person parent;
@Column(name = "parent")
private Integer parentId;

Basically, I would like the following:

System.out.println(element.getParentId());
System.out.println(element.getParent().getId());
element.setParentId(2);
System.out.println(element.getParentId());
System.out.println(element.getParent().getId());

This to print "3,3,2,2" instead of "3,3,2,3".

Is it possible (without writing a custom lazy-loading on the getParent() getter?)

Thx in advance

like image 274
SzaboAdam Avatar asked Sep 30 '22 22:09

SzaboAdam


2 Answers

IIRC, Hibernate will not do that for you. You're the one responsible if you have something like that (I remembered doing something similiar).

The first solution will be to save the entity first, then refresh using the entity manager.

element.setParentId(2);
entityManager.merge(element);
entityManager.refresh(element);

Refresh will make it fetch the object from the database again, and it will have the correct value.

The second option which I did, was to change the setter of the entity to maintain the state. Something like:

public void setParent(Parent parent) {
    this.parent = parent;
    parentId = parent.id;
}
like image 200
Rowanto Avatar answered Oct 04 '22 03:10

Rowanto


Try this

@JoinColumn(referencedColumnName = "id", insertable = false, name = "parent")
@ManyToOne(fetch = FetchType.LAZY)
private Person parent;


@Column(name = "parent")
private Integer parentId;

If that don't work:

Try this if parentId is the primary key of the Parent entity:

@JoinColumn(referencedColumnName = "id", insertable = false, name = "parent")
@ManyToOne(fetch = FetchType.LAZY)
private Person parent;

@Id
@GeneratedValue(strategy = GenerateType.AUTO)
@Column(name = "parent")
private Integer parentId;

Try this:

@JoinColumn(referencedColumnName = "id", name = "parent")
@ManyToOne(fetch = FetchType.LAZY)
private Person parent;


@Column(name = "parent")
private Integer parentId;

If that don't work:

Try this:

@JoinColumn(name = "parent")
@ManyToOne(fetch = FetchType.LAZY)
private Person parent;


@Column(name = "parent")
private Integer parentId;
like image 22
Rika Avatar answered Oct 04 '22 02:10

Rika