JPA getReference在我的对象中设置了一个错误的id(总是设置为零)

时间:2016-04-29 08:19:52

标签: java jpa

我正在使用JPA EntityManager.getReference(Class clazz, Integer pk)。 我知道pk值设置为1但仍然在方法返回的对象中,该值设置为零。我不明白为什么。

这是我的代码:

@Component
public class TypeDAO extends MainDAO {

    public TypeDTO simpleProxyRetrieveByIdType(int id){
        TypeDTO type = simpleProxyRetrieveById(TypeDTO.class, id);
        return type;
    }
}

我的MainDAO课程:

static protected <E> E simpleProxyRetrieveById(Class <E> clazz, Integer id) {
    EntityManager em = emFactory.createEntityManager();
    E item = em.getReference(clazz, id);
    em.close();
    return item;
}

以下是TypeDTO类:

@Entity
@Table(name = "type_livr")
public class TypeDTO {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "type_livraison_id")
    private int id;
        public int getId() {return id;}
        public void setId(int id) {this.id = id;}

    @Column(name = "code")
    private int code;
    public int getCode() {return code;}
    public void setCode(int code) {this.code = code;}

    @Column(name = "libelle_court")
    private String libelleCourt;
        public String getLibelleCourt() {return libelleCourt;}
        public void setLibelleCourt(String libelleCourt) {this.libelleCourt = libelleCourt;}

    @Column(name = "libelle_long")
    private String libelleLong;
        public String getLibelleLong() {return libelleLong;}
        public void setLibelleLong(String libelleLong) {this.libelleLong = libelleLong;}

    @OneToMany(mappedBy = "type")
    private List<LivraisonDTO> typeLivr;
        public List<LivraisonDTO> getTypeLivr() {return typeLivr;}
        public void setTypeLivr(List<LivraisonDTO> typeLivr) {this.typeLivr = typeLivr;}

    public TypeDTO() {
    }

    public TypeDTO(int id, int code, String libelleCourt, String libelleLong) {
        this.id = id;
        this.code = code;
        this.libelleCourt = libelleCourt;
        this.libelleLong = libelleLong;
    }   
}

感谢您的回答。

1 个答案:

答案 0 :(得分:0)

事实上没有问题:

在你调用getId()getter之前,

id并没有真正初始化为真实的id。

您应该只在调试器中检查过!