如何将字段一到多个的多个表映射到Java中的同一表?

时间:2019-04-09 09:42:30

标签: java hibernate jpa

我需要解决一个休眠映射,我有一个公用表,其中包含到表A,B和C的多对音(一个表只能有一个多对音)

然后我通过放置每个表的ID来映射它来解决它。 有没有更好的方法来执行此映射?因为我有3个以上的表可以重复使用同一张表

SCHEMA

1 个答案:

答案 0 :(得分:0)

公用表

包含一对多映射

@Entity
    @Table(name= "common")
    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
                      property  = "id",
                      scope     = Long.class)
    @DynamicInsert(true)
    @DynamicUpdate(true)
    public class Common implements Serializable {

        private static final long serialVersionUID = 6953927535242022811L;

        @Id
        @Column(name= "id")
        private Long id = Long.parseLong(UUID.randomUUID().toString().substring(0, 8), 16);


        @OneToMany(cascade= CascadeType.ALL, mappedBy= "a_id", orphanRemoval= true )
        @LazyCollection(LazyCollectionOption.FALSE)
        private List<A> aList;

        @OneToMany(cascade= CascadeType.ALL, mappedBy= "b_id", orphanRemoval= true )
        @LazyCollection(LazyCollectionOption.FALSE)
        private List<B> bList;

        @OneToMany(cascade= CascadeType.ALL, mappedBy= "c_id", orphanRemoval= true )
        @LazyCollection(LazyCollectionOption.FALSE)
        private List<C> cList;

        // getter and setters
    }

表A

@Entity
@Table(name= "a")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,
                  property  = "id",
                  scope     = Long.class)
@DynamicInsert(true)
@DynamicUpdate(true)
public class A implements Serializable {

    private static final long serialVersionUID = 6953927535242022811L;

    @Id
    @Column(name= "id")
    private Long id = Long.parseLong(UUID.randomUUID().toString().substring(0, 8), 16);

    @ManyToOne(optional=false)
    @JoinColumn(name= "common_id")
    private Common CommonId;  //many to one is option if you required 

}

B和C的类似实现