EntityNotFoundException in Hibernate Many To One mapping however data exist

SpringHibernateJpaSpring Data-Jpa

Spring Problem Overview


I am getting javax.persistence.EntityNotFoundException error when I am trying to get User through Invoice object

invoice.getUser().getId()

Error is as follows

javax.persistence.EntityNotFoundException: Unable to find com.indianretailshop.domain.User with id 5
	at org.hibernate.ejb.Ejb3Configuration$Ejb3EntityNotFoundDelegate.handleEntityNotFound(Ejb3Configuration.java:137)
	at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:189)
	at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:178)
	at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)

Entity classes are as follows(getters and setters are not included)

@Entity
@Table(name="users")
public class User implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(unique=true, nullable=false)
	private int id;

	.
        .
        .

	//bi-directional many-to-one association to Invoice
	@OneToMany(mappedBy="user")
	private List<Invoice> invoices;
}

@Entity
@Table(name="invoice")
public class Invoice implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(unique=true, nullable=false)
	private int id;
        .
        .
        .

	//bi-directional many-to-one association to User
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="Users_id")
	private User user;
}

Spring Solutions


Solution 1 - Spring

I had the same problem, and

@NotFound(action = NotFoundAction.IGNORE)

solved my problem.

Solution 2 - Spring

If you use @ManyToOne, the referenced entity must exist. The only other option is to specify that field as a long and retrieve the referenced entity by means of a separate query.

Throws an exception (javax.persistence.EntityNotFoundException) instead of returning null if it can't find the requested entity.

Use @NotFound annotation to resolve this exception if you are lazy loading and not handling this exception manually.

 @ManyToOne(
        fetch = FetchType.LAZY)
    @NotFound(
        action = NotFoundAction.IGNORE)
    @JoinColumn(
        name = COLUMN,
        referencedColumnName = COLUMN,
        insertable = false,
        updatable = false)
    private Table table;

Solution 3 - Spring

The problem could be that the direct entity does not exist, but also it could be that the referenced entity from that entity, normally for a EAGER fetch type, or optional=false.

Try this:

     //bi-directional many-to-one association to User
     @ManyToOne(fetch=FetchType.LAZY)
     @JoinColumn(name="Users_id")
     private User user = new User();

Solution 4 - Spring

Not sure if that applies to your case.

But I had a similar issue where I updated directly in the database table X and set a field null, but in java class the field was @NotNull.

So when another class Y had a X object with ManyToOne, it wasn't able to load the entity because of the null value in the entity.

Solution 5 - Spring

please try the following

@OneToMany(mappedBy="yourMappingattributeName",cascade=CascadeType.ALL) or

@OneToMany(mappedBy="yourMappingattributeName",cascade=CascadeType.MERGE)

Solution 6 - Spring

I had the similar issue recently, but the problem is that record is always existed in DB. So I did some investigation, found out that at some point that cached entity is marked as removal and reload failed before reloading from DB. It happened in Hibernate 4.3.5 Final for me Then I upgrade to Hibernate 4.3.11 Final which seems to fix the issue.

Solution 7 - Spring

Use @NotFound(action = NotFoundAction.IGNORE) in case it's parent not exist

By using cascade=CascadeType.ALL it will delete it's parent entity

Solution 8 - Spring

Maybe one comes to this answer and finds it useful: In my case, I have marked my entity as deleted and entity who is relationship with this entity could not find it. So, changing deleted to false worked for me.

Solution 9 - Spring

It should work when you add referencedColumnName = COLUMN in @JoinColumns of @ManyToOne annotation

Solution 10 - Spring

You must implement hashCode and equals methods for all entities. Example:

@Override
public int hashCode() {
    return Objects.hash(getId());
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBadal SinghView Question on Stackoverflow
Solution 1 - SpringozerayView Answer on Stackoverflow
Solution 2 - Springshane leeView Answer on Stackoverflow
Solution 3 - Springrajesh kakawatView Answer on Stackoverflow
Solution 4 - Springuser3450922View Answer on Stackoverflow
Solution 5 - SpringHaroonView Answer on Stackoverflow
Solution 6 - Springsendon1982View Answer on Stackoverflow
Solution 7 - SpringShahid Hussain AbbasiView Answer on Stackoverflow
Solution 8 - SpringKhasan 24-7View Answer on Stackoverflow
Solution 9 - SpringdavidleongzView Answer on Stackoverflow
Solution 10 - SpringSherView Answer on Stackoverflow