JPA Annotation @OneToMany关系不同记录

时间:2017-01-18 22:24:32

标签: java hibernate jpa persistence one-to-many

我有两个实体 - 软件和员工 - 具有oneToMany关系,并且它们处于同一级别。

@Entity(name = "EMPLOYEE") 
public class Employee {

        private long employeeId;
        private String firstName;
        private String lastName;
        private List<Software> software;


        @Id //signifies the primary key
        @Column(name = "EMPLOYEE_ID", nullable = false)
        @GeneratedValue(strategy = GenerationType.AUTO)
        public long getEmployeeId() {
            return employeeId;
        }

        public void setEmployeeId(long employeeId) {
            this.employeeId = employeeId;
        }

        @Column(name = "FIRST_NAME", length = 50)
        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        @Column(name = "LAST_NAME", nullable = false,length = 50)
        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }

        @OneToMany(
              fetch = FetchType.EAGER,
              cascade = CascadeType.ALL,
              orphanRemoval = true,
              targetEntity = Software.class)
        @Fetch(FetchMode.SUBSELECT)
        public List<Software> getSoftware() {
            return software;
        }

        public void setSoftware(Software software) {
            this.software = software;
        }
}

Software.class

@Entity(name = "SOFTWARE") 
public class SOFTWARE {

    private long softwareId;
    private String softwareName;
    private String version; 
    private Employee emp;

    @Id 
    @Column(name = "SOFTWARE_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long getSoftwareId() {
        return softwareId;
    }

    public void setSoftwareId(long softwareId) {
        this.softwareId = softwareId;
    }

    @Column(name = "SOFTWARE_NAME")  
    public String getSoftwareName() {
        return softwareName;
    }

    public void setSoftwareName(String name) {
        this.name = name;
    }

    @Column(name = "SOFTWARE_VERSION")  
    public String getSoftwareVersion() {
        return softwareDesc;
    }

    public void setSoftwareVersion(String version) {
        this.version = version;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "EMPLOYEE_ID", nullable = true)
    public String getEmployee() {
        return emp;
    }

    public void setEmployee(Employee emp) {
        this.emp = emp;
    }
}

我们的想法是拥有一个带有软件列表的gui,其中记录可以被删除,添加并分配给每个员工。

enter image description here

在我的情况下,我将拥有重复的软件记录,这些记录仅在employee_id上​​有所不同。问题是如果我编辑一个记录它不会影响所有记录,如果我删除该关系我不想删除该记录本身,因为如果它被删除我不能将该软件分配给另一个员工。

这是正确的方法还是可以通过创建第三个表来解决问题@JoinTable? 有人有想法吗?

1 个答案:

答案 0 :(得分:1)

请勿使用CascadeType.ALL。这将包括级联删除操作的效果,如果删除员工,相关的软件记录也将被删除。我从没有级联开始。