同一对象的两种表示形式-休眠问题

时间:2018-11-12 16:10:10

标签: java spring hibernate

我有一条select语句,它以与File一对多的关系加载到Folders类中。尽管有时会发生错误,但有时会给我一个Hibernate错误,说我对会话的使用是不安全的,或者同一集合Folders.file有两种表示形式。我究竟做错了什么?感谢您的帮助!

Folders.java

   @Entity
   @Table(name= "folders")

   public class Folders implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "folder_code")
    private Integer folderCode;

    @Column(name = "assign_code")
    private Integer assignCode;

    public Set<File> getFile() {
        return file;
    }


    public void setFile(Set<file> assignments) {
        this.file = file;
    }


    @OneToMany(targetEntity=File.class,cascade=CascadeType.ALL,fetch=FetchType.EAGER)
    @JoinColumn(name="assign_code",referencedColumnName="assign_code")
    Set<Folder> folder;

    public Integer getAssignCode() {
        return assignCode;
    }


    public void setAssignCode(Integer assignCode) {
        this.assignCode = assignCode;
    }

    public Integer getFolderCode() {
        return folderCode;
    }

    public void setFolderCode(Integer folderCode) {
        this.folderCode = folderCode;
    }

    public Date retrieveFileStartDate(){
        List<File> file;
        if(this.getFile()!=null){
            file= new ArrayList<File>(this.getFile());
        }else{
            file = new ArrayList<File>();
        }
        return file.size()>0 ? new 
        Date(file.get(0).getStartDate()): null;
    }



}

File.java

@Entity
@Table(name= "file")

public class File implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "assign_code")
    private Integer assignCode;


    @Column(name = "start_date")
    private String startDate;

    @Column(name = "end_date")
    private String endDate;


    public Integer getAssignCode() {
        return assignCode;
    }


    public void setAssignCode(Integer assignCode) {
        this.assignCode = assignCode;
    }


    public String getStartDate() {
        return startDate;
    }


    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }


    public String getEndDate() {
        return endDate;
    }


    public void setEndDate(String endDate) {
        this.endDate = endDate;
    }



}

1 个答案:

答案 0 :(得分:0)

我不确定您遇到的错误,但查看您的实体,我可以说关系映射不正确。

您要在Folder实体中映射@OneToMany,但在File实体中映射@ManyToOne呢?

还定义mappingBy属性以使其正常工作。

Folder.java

@OneToMany(targetEntity=File.class,cascade=CascadeType.ALL,fetch=FetchType.EAGER,mappedBy="file")
@JoinColumn(name="assign_code",referencedColumnName="assign_code")
private Set<Folder> folder;

File.java

@ManyToOne
private File file;
//getter and setter