springjpa,一个多域引用主键的一部分

dgiusagp  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(345)

给一个班

@Entity
@Table(name = "ATABLE")
public class A implements Serializable {
    public static final String DB_ID = "AID";
    public static final String DB_MARKET = "AMARKET";

    @EmbeddedId
    @AttributeOverrides({
            @AttributeOverride(name = "id", column = @Column(name = DB_ID)),
            @AttributeOverride(name = "market", column = @Column(name = DB_MARKET))
    })
    public AIdClass id;

    @OneToMany
    @JoinColumn(name = B.DB_MARKET, referencedColumnName = DB_MARKET, insertable = false, updatable = false)
    public List<B> bs;
}

和b级

@Entity
@Table(name = "BTABLE")
public class B implements Serializable {
    public static final String DB_ID = "BID";
    public static final String DB_MARKET = "BMARKET";

    @EmbeddedId
    @AttributeOverrides({
            @AttributeOverride(name = "id", column = @Column(name = DB_ID)),
            @AttributeOverride(name = "market", column = @Column(name = DB_MARKET))
    })
    public BIdClass id;
}

可以列出每个实体,但使用 @OneToMany 关系不会引发以下错误
org.springframework.beans.factory.beancreationexception:创建名为“entitymanagerfactory”的bean时出错
原因:org.hibernate.annotationexception:无法Map集合fr.zzz.domain.a.bs
原因:org.hibernate.annotationexception:fr.zzz.domain.a.bs引用fr.zzz.domain.b的referencedcolumnnames(amarket)未Map到单个属性
A 实体与多个 BA.AMARKET = B.BMARKET

eagi6jfj

eagi6jfj1#

出现此问题是因为在keys amarket=bmarket上执行连接时,组合键(aid,amarket)和(bid,bmarket)可能不是唯一的。因此你得到了错误 not mapped to a single property . 请与我忍受,使用以下样本数据来分析问题;
对于表a

AID  AMARKET 
 1      1       
 2      1    
 3      2

对于表b

BID  BMARKET
 1      1   
 2      2
 3      2

上面的场景是完全可能的(至少在数据库级别上),并且只需使用 AMARKET 以及 BMARKET 加入 @OneToMany 这是不可能的。但可能的是使用 @ManyToMany ,这将立即解决问题,如果表结构是正确的。
但如果需要使用呢 @OneToMany 由于一些业务限制。然后必须更新表b以包含 A.AID 并添加外键约束以确保数据完整性。则只有结果集对关系有效 @OneToMany . 连接方式如下:;

@OneToMany
@JoinColumn(name = B.DB_AID, referencedColumnName = DB_ID)
@JoinColumn(name = B.DB_MARKET, referencedColumnName = DB_MARKET)
public List<B> bs;

在b中:

@Entity
@Table(name = "BTABLE")
public class B implements Serializable {
    public static final String DB_ID = "BID";
    public static final String DB_MARKET = "BMARKET";
    public static final String DB_AID = "AID";

    @EmbeddedId
    @AttributeOverrides({
            @AttributeOverride(name = "id", column = @Column(name = DB_ID)),
            @AttributeOverride(name = "market", column = @Column(name = DB_MARKET))
    })
    public BIdClass id;

    @Column(name = DB_AID)
    private Long aid; // assuming aid is a Long
}

现在,连接是在a的复合主键上完成的。

相关问题