我在我的sql server 2016数据库中有三个表作为Hibernate应用程序的示例,该应用程序使用带有附加列的连接表来分配从具有特定数量的客户购买的文章。我在DB中的表是:
table_article (a_id int, description varchar(255))
a_id description
1 fish
2 fish
3 water
table_customer (customer_id int, name varchar(255)
customer_id name
1 john
2 jane
3 jack
ac_join_table (a_id, customer_id, amount, pk(a_id, customer_id))
a_id customer_id amount
1 2 10
2 1 3
2 3 7
2 2 18
3 1 5
因此,身份2的顾客jane购买10条鱼。如果我运行我的程序,看起来连接表中的表列被解释为不同或交换。因为如果我运行以下代码jane购买3条鱼,18条鱼和7条鱼。如果我运行,看起来article_id被解释为customer_id:
// should return that jane (customer_id: 2) buys 10 fishes (a_id: 1, amount: 10)
// but it interprets a_id as customer_id so jane buys 3, 7 and 18 fishes...
Cust c = sessionObj.get(Cust.class, 2);
List<ArtCustJoin> articles = c.getArtikel();
for (ArtCustJoin artCustJoin : articles) {
System.out.println(artCustJoin.getArt().getDescription());
}
我的Hibernate模型的Java类是:
table_article的Art.java
@Entity
@Table(name="table_article")
public class Art {
@Id
@Column(name = "a_id")
private int article_id;
@Column
private String description;
// …
@OneToMany(mappedBy="ku")
private List<ArtCustJoin> customers;
// …
// getters and setters
// ...
}
table_customer的Cust.java
@Entity
@Table(name="table_customer")
public class Cust {
@Id
private int customer_id;
@Column
private String name;
@OneToMany(mappedBy="art")
private List<ArtCustJoin> artikel;
// getter + setter
// ...
}
ArtCustJoin.java用于连接表ac_join_table。连接表有一个额外的列数
@Entity
@Table(schema="dbo", name="ac_join_table")
public class ArtCustJoin {
// Use Compound Key instead of single primitive key
@EmbeddedId
CompositeKey id;
@ManyToOne
@JoinColumn(name="a_id", columnDefinition="int", foreignKey = @ForeignKey(name = "FK_ARTID"))
@MapsId("article_id") // maps to attribute with this name in class Artikel
private Art art;
@ManyToOne
@JoinColumn(name="customer_id", foreignKey = @ForeignKey(name = "FK_CUSTID"))
@MapsId("customer_id") // maps to attribute with this name in class Kunde
private Cust ku;
@Column
private int amount;
public CompositeKey getId() {
return id;
}
public void setId(CompositeKey id) {
this.id = id;
}
// getter + setter
// ...
}
还有一个复合键的类:
@Embeddable
public class CompositeKey implements Serializable{
@Column
private Integer a_id;
@Column
private Integer customer_id;
public CompositeKey() {}
// ...
}
我不知道错误是哪一列a_id被解释为customer_id ...
我不是Java开发人员,但两个@OneToMany(mappedBy=
看起来都很奇怪,看起来就像问题的原因。不是Customer
应该被ArtCustJoin
映射到customer_id
吗?而不是@OneToMany(mappedBy="art")
。这同样适用于Art
类。