60

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;
}
Community
  • 1
  • 1
Badal Singh
  • 918
  • 1
  • 6
  • 13
  • To get an answer you need to provide some more information, for example: what exactly do you do?, complete stacktrace... And double check that the entity really exists in the database. – Ralph Nov 24 '12 at 11:58
  • Do you have foreign keys defined from your invoice table to the user table? As @Ralph stated, you should check that the given user (with id 5) actually exists. – Perception Nov 24 '12 at 16:34
  • It was working when I was using LAZY fetch, and yes there are entity in database. I dont understand why it is not working in EAGER fetch, rest of the code is same as before. For now I am using LAZY fetch as temporary change to resolve the issue. – Badal Singh Dec 07 '12 at 18:24
  • 1
    I have never defined the id using setid() method which means it is getting the id from database only and their is a foreign key exist in database. Is it a bug in hibernate – Badal Singh Dec 07 '12 at 18:26
  • And I also noticed if I create two invoices in database then even EAGAR fetch is working so the issue is only seems to exist with exactly one invoice record for one user. – Badal Singh Dec 07 '12 at 18:28
  • https://stackoverflow.com/questions/73234549/javax-persistence-entitynotfoundexception-unable-to-find-entity-with-id – KJEjava48 Aug 05 '22 at 07:04

11 Answers11

122

I had the same problem, and

@NotFound(action = NotFoundAction.IGNORE)

solved my problem.

ozeray
  • 2,134
  • 2
  • 18
  • 13
  • 5
    @dirai I did not try it. NotFound is anyway practical when you don't mind whether the associated entity exists or not. – ozeray Feb 05 '18 at 09:07
  • 1
    The only problem with this is that this fails silently. Has anyone found a better solution that handles this error gracefully while also logging the missing link? – VSZM Aug 17 '18 at 08:51
  • when using be aware that this causes performance issues! fixing inconsistent data does the job. – kleenxcoder Apr 01 '20 at 15:06
  • With this, for me, Hibernate is logging: "13:51:14.466 WARN [main] o.h.c.AnnotationBinder - HHH000491: The [...] association in the [...] entity uses both @NotFound(action = NotFoundAction.IGNORE) and FetchType.LAZY. The NotFoundAction.IGNORE @ ManyToOne and @ OneToOne associations are always fetched eagerly." – Nick Pruehs Sep 12 '22 at 11:53
48

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;
shane lee
  • 1,290
  • 15
  • 17
38

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();
Joe
  • 7,749
  • 19
  • 60
  • 110
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
  • Earlier I was using LAZY fetch only then it was working and it is not working in EAGER fetch which I don't understand. – Badal Singh Dec 07 '12 at 18:19
  • Is this a bug or something which I should report. – Badal Singh Dec 07 '12 at 18:20
  • @kakawat I have same problem as above, but the code is not in our control, I have deleted some rows in the database, does improper data cause this kind of error – gurusai Sep 10 '15 at 04:48
  • I need it to be @ManyToOne(fetch = FetchType.EAGER) and @JsonIgnore – Stéphane GRILLON Sep 20 '15 at 14:32
  • 2
    The Lazy fetch just ends up kicking the error can down the road as when you try to lead the thing that would have been eager fetched you end up with a LazyLoadException. I wish I could understand why it fails to begin with. I am running Hibernate 5.0.11 in Spring Boot 1.5.1 – haskovec Feb 07 '17 at 22:10
  • 2
    I am facing the same problem and FetchType.Lazy doesn't solve my problem. In my case the relationship is not bidirectional and I only have the @ManyToOne declared. I am using java-ee-api-7.0.jar for the JPA and not Hibernate. Only if I give NotFoundannotation the exception does not occur. Any idea what I might be doing wrong? – raikumardipak Feb 03 '18 at 16:44
  • In my case I had forgotten to remove @Notnull from the field which was causing this problem. – Ehsan Waris Feb 25 '20 at 08:16
  • This worked for me but i still dont understand why. Someone can help? – Higarian Jun 23 '20 at 01:16
  • https://stackoverflow.com/questions/73234549/javax-persistence-entitynotfoundexception-unable-to-find-entity-with-id – KJEjava48 Aug 05 '22 at 07:04
10

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.

user3450922
  • 111
  • 1
  • 5
  • 5
    Thanks, this was my problem. Look for `@NotNull` and `@JoinColumn([...]nullable = false)`. – Nergal Nov 22 '18 at 13:36
  • @Negal, your comment was de facto the only real explanation to the issue in this thread. The other top rated answers are just workarounds. – Wecherowski Jul 16 '20 at 20:36
7

please try the following

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

@OneToMany(mappedBy="yourMappingattributeName",cascade=CascadeType.MERGE)
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Haroon
  • 111
  • 1
  • 3
4

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.

sendon1982
  • 9,982
  • 61
  • 44
4

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

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

Shahid Hussain Abbasi
  • 2,508
  • 16
  • 10
  • I had the same issue with a ManyToOne, lazy loaded. When I added the `@NotFound(action = NotFoundAction.IGNORE)` it resolved the problem. – Philippe May 14 '19 at 15:00
0

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.

Khasan 24-7
  • 456
  • 2
  • 5
  • 19
0

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

mw509
  • 1,957
  • 1
  • 19
  • 25
davidleongz
  • 155
  • 2
  • 11
0

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

@Override
public int hashCode() {
    return Objects.hash(getId());
}
Sher
  • 116
  • 2
0

You can now add optional = true to the @ManyToOne annotation and nullable = true to the @JoinColumn. You dont need to swallow the exception. Seems JPA has improved a bit since this question was first posted.

Example

@ManyToOne(optional = true)
@JoinColumn(name = "user_id", referencedColumnName = "id", nullable = true)
Usman Mutawakil
  • 4,993
  • 9
  • 43
  • 80