gpt4 book ai didi

java - Hibernate - 从我的示例表中获取错误的实体。看起来表列是 "exchanged"

转载 作者:行者123 更新时间:2023-12-02 10:51:11 25 4
gpt4 key购买 nike

我的 sql server 2016 数据库中有三个表作为 Hibernate 应用程序的示例,该应用程序使用带有附加列的连接表来分配从客户购买的特定金额的文章。我在数据库中的表是:

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

因此 ID 为 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 by customer_id? 而不是 @OneToMany(mappedBy="art")。这同样适用于 Art 类.

关于java - Hibernate - 从我的示例表中获取错误的实体。看起来表列是 "exchanged",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52169464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com