小编典典

Hibernate多对一映射中的EntityNotFoundException但是存在数据

hibernate

尝试通过Invoice对象获取用户时出现javax.persistence.EntityNotFoundException错误

invoice.getUser()。getId()

错误如下

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)

实体类如下(不包括getter和setter)

@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;
}

阅读 512

收藏
2020-06-20

共1个答案

小编典典

问题可能是直接实体不存在,也可能是该实体中的引用实体,通常用于EAGER访存类型,或optional = false。

尝试这个:

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