In Wildfly 8.2.0 (which user more older version of hibernate) I used org.hibernate.bytecode.internal.javassist.FieldHandled and org.hibernate.bytecode.internal.javassist.FieldHandler but these classes not exist in hibernate 5.1.10
Can you advice please how to switch on lazy-loading mode ?
Lazy loading works except for the parent side of a @OneToOne association. This is because Hibernate has no other way of knowing whether to assign a null or a Proxy to this variable. More details you can find in this article.
Or, you can just remove the parent side and use the client side with @MapsId as explained in this article. This way, you will find that you don’t really need the parent side since the child shares the same id with the parent so you can easily fetch the child by knowing the parent id.
I can’t remove reference to child object on parent side.
I solved the problem by adding “optional = false” to all my OneToOne relations.
Works fine, but I don’t understand why does it work. Can you explain please ?
Suppose I take this solution and remove reference to “deviceRegistration” from “DeviceEntity”. You wrote:
DeviceEntity deviceEntity = …
DeviceRegistrationEntity dre = entityManager.find(DeviceRegistrationEntity.class, deviceEntity.getId());
As far as I know, “find” function of EntityManager works by primary key. In my case primary key of DeviceRegistrationEntity is not the same as DeviceEntity, it has it’s own ID field, it also has
A one-to-one association without sharing the PK is a design smell. According to database table relationship, a one-to-one association always shares the PK.
In your case, unless you change your design, you’ll have to stick to using a separate PK which doubles the amount of memory that requires indexing since you need an index for the PK and another one for the FK.
Hi @vlad thanks for the great solutions. Its always good to read your articles. I have one question - what if we have more than one “OneToOne” mappings? The @MapsId won’t be applicable in that case, right?
@Entity
public class pet implements Serializable
{
@Id
//@ManyToOne(targetEntity = human.class)
//@JoinColumn(name="id")
public long id;
public String name;
}
human Entity
@Id
@Column(name="id")
private int id;
@Column(name="name", length=20, nullable=true)
private String name;
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="id")
public List<pet> pets = new ArrayList<>();
public human(int id, String name)
{
this.name = name;
this.id = id;
}
public human()
{
}