双向模型的JPA映射

时间:2018-09-10 21:30:14

标签: hibernate jpa orm spring-data-jpa hibernate-mapping

我有两个表Parent和Child。我希望在父级(单向)中创建父级的“ id”和“ uuid”列时都将其写入Child。通过遵循以下Postgres和Spring Data JPA的模型/注释组合,我看不到每个父记录的子表中的2个条目,请帮助:

Parent.java:

import lombok.Data;
import lombok.ToString;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "parent")
@Data
@ToString(exclude = {"child"})
public class Parent implements Serializable {

    private static final long serialVersionUID = 145286864858301707L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "parentSequence")
    @SequenceGenerator(sequenceName = "parent_seq", allocationSize = 1, name = "parentSequence")
    @Column(name = "id")
    private Long id;

    @NotNull
    @Column(name = "uuid", nullable = false)
    private String uuid;

    @OneToMany(
            targetEntity = Child.class,
            mappedBy = "parent",
            cascade = CascadeType.ALL,
            orphanRemoval = true)
    private List<Child> child = new ArrayList<>();
}



Child.java:

import lombok.Data;
import lombok.ToString;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Entity
@Table(name = "child")
@Data
@ToString(exclude = "parent")
public class Child implements Serializable {

    private static final long serialVersionUID = 2925636680004485119L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "childSequence")
    @SequenceGenerator(sequenceName = "child_seq", allocationSize = 1, name = "childSequence")
    @Column(name = "id")
    private Long id;

    @NotNull
    @Column(name = "uuid", nullable = false)
    private String uuid;

    @ManyToOne(
            targetEntity = NatEntity.class,
            fetch = FetchType.LAZY)
    @JoinColumns({
            @JoinColumn(name = "parent_id", referencedColumnName = "id"),
            @JoinColumn(name = "parent_uuid", referencedColumnName = "uuid")
    })
    private Parent parent;
}

0 个答案:

没有答案