JPA oneToMany 級聯更新

 oneToMany 使用:java

示例:Employee與Phone爲例.app

一、類定義以下:dom

package com.vrvwh.wh01.domain;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by Administrator on 2015/3/5.
 */
@Entity
public class Employee {
    private long id;

    private String name;

    private Set<Phone> phones=new HashSet<Phone>();

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Column
    public String getName() {
        return name;
    }

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

  /**orphanRemoval=true配置代表刪除無關聯的數據。級聯更新子結果集時此配置最關鍵
  */ @OneToMany(mappedBy
= "employee",cascade = CascadeType.ALL,orphanRemoval = true) public Set<Phone> getPhones() { return phones; } public void setPhones(Set<Phone> phones) { this.phones = phones; } }

package com.vrvwh.wh01.domain;

import javax.persistence.*;

/**
 * Created by Administrator on 2015/3/5.
 */
@Entity(name="Phones")
public class Phone {
    @Id
    private int phoneId;
    private int phoneNumber;

    @ManyToOne(cascade= CascadeType.ALL)
    private Employee employee;

    public int getPhoneId() {
        return phoneId;
    }
    public void setPhoneId(int phoneId) {
        this.phoneId = phoneId;
    }
    public int getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(int phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
    public Employee getEmployee() {
        return employee;
    }
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }

}

二、更新:this

Employee employee=employeeService.query(1);
        employee.getPhones().clear();
        Phone phone1=new Phone();
        phone1.setPhoneNumber(132567);
        employee.getPhones().add(phone1);
        Phone phone2=new Phone();
        phone2.setPhoneNumber(132567);
        employee.getPhones().add(phone2);
        employeeService.update(employee);
相關文章
相關標籤/搜索