OneToOne + No Foreginkey + Unidirectional + Datamissing => EntityNotFoundException

From the inherited system, we have 1 table (Entity) and 1 view (UserDetail) without restrictions, but with relationships.

Entity | Id | Desc | Created_By |... UserDetail | UserId | F_Name | L_Name |... 

CreatedBy has the identifier of the user who created this object. We have a one-way mapping in Entity.java, as shown below.

 @OneToOne @JoinColumn(name = "CREATED_BY", referencedColumnName = "USER_ID") private UserDetail createdBy; 

Problem

But since its an outdated system, we have no control over this, and the user is very remote.

When entityReposity.findAll is called, the following error is called

 org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find com...UserDetail with id 92237; nested exception is javax.persistence.EntityNotFoundException: Unable to find com...UserDetail with id 92237 

Question

How to make JPA consider this association to be optional or is there some way in JPA to ignore it (e.g. @NotFound in Hibernate)?

I tried

  • @NotFound works, but we need to hack @OneToOne like @ManyToOne. We also want to implement a solution independent of the implementation. Note also this error, https://hibernate.atlassian.net/browse/ANN-725

  • optional = true - if this worked in accordance with the syntactic value of how it should behave, I would not write this.

  • Also tried postLoad () in UserDetails.java.

  • @PostLoad Solution We have an exception handler and the exception is caught there before @PostLoad is called in the Entity class.

In Entity.java

  @PostLoad public void postLoad(){ try { System.out.println(this.getCreatedBy()); //Before control comes here, it goes to aop exception handler } catch (EntityNotFoundException e){ setCreatedBy(null); } } 

Any help would be appreciated.

+7
java oracle11g hibernate jpa one-to-one
source share
1 answer

As crazy as that sounds, you need to create an association @OneToOne optional = false . See this question and answer for an explanation.

Thus, the code for the association will be:

 @OneToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "CREATED_BY", referencedColumnName = "USER_ID") private UserDetail createdBy; 

Of course, the problem is that if you try to access the createdBy related association, then Hibernate will try to lazily load the associated Entity, and you will get the same exception.

@NotFound really the best choice.

+3
source share

All Articles