必威体育Betway必威体育官网
当前位置:首页 > IT技术

JPA OneToMany级联更新 及 orphanRemoval = true 说明

时间:2019-06-20 21:45:16来源:IT技术作者:seo实验室小编阅读:55次「手机版」
 

orphanremoval

下面是一个例子:

Employee ---- Address (假设为单向one-to-many)

class Employee {

@oneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true)

@JoinTable(JoinColumn="Employee_id")

private Set<Address> addresses;

// [当Employee和Address均处于关联时]这种场合设置cascade和orphanRemoval是一样的效果,只要设置一种就好

// [当Employee和Address均不处于关联时,比如设置address中某条数据为空, 仅设置Cascade=Remove时,当操作到Employee只会将其对应的Address删掉

// 设置orphanRemoval=true时,会将FK上Null对应的数据都会删掉(自动去孤子)

}

注意加入的位置

只能在one的一方设置orphanRemoval

cascade所有关系都可设置

oneToMany 使用:

示例:Employee与Phone为例.

1、类定义如下:

复制代码

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

}

复制代码

2、更新:

复制代码

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

复制代码

相关阅读

springdata jpa使用Example快速实现动态查询

Example官方介绍 Query by Example (QBE) is a user-friendly querying technique with a simple interface. It allows dynamic

如何对 JPA 或者 MyBatis 进行技术选型

在我们平时的项目中,大家都知道可以使用 JPA 或者 Mybatis 作为 ORM 层。对 JPA 和 Mybatis 如何进行技术选型? 下面看看大精华总结

分享到:

栏目导航

推荐阅读

热门阅读