Hibernate多对一映射中的EntityNotFoundException但是数据存在 [英] EntityNotFoundException in Hibernate Many To One mapping however data exist

查看:22
本文介绍了Hibernate多对一映射中的EntityNotFoundException但是数据存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试通过 Invoice 对象获取 User 时出现 javax.persistence.EntityNotFoundException 错误

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

invoice.getUser().getId()

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

推荐答案

问题可能是直接实体不存在,也可能是来自该实体的引用实体,通常用于 EAGER 获取类型,或可选=假.

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.

试试这个:

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

这篇关于Hibernate多对一映射中的EntityNotFoundException但是数据存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆