gpt4 book ai didi

java - 为什么无法使用 JPA TopLink 注释连接第三个表?

转载 作者:行者123 更新时间:2023-12-01 15:58:44 25 4
gpt4 key购买 nike

我有简单的 3 个表:

Users
-id
-name

Addresses
-id
-user_id //FK
-location

Phone
-id
-number
-address_id //FK
  • 用户可以拥有多个地址
  • 地址可以有多个电话

因此,应用于每个实体类的注释将如下所示:

用户

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private List<Addresses> addresses;

地址

    @ManyToOne()
@JoinColumn(name = "user_id")
private Users user;

@OneToMany(mappedBy = "address")
private List<Phone> phone;

电话

    @ManyToOne()
@JoinColumn(name = "address_id")
private Addresses address;

上面的注释应该创建关系:

users  (1) ----- (n) addresses (1) ------ (n) phone

然后我在 MySQL 中创建了一些测试数据,并尝试运行测试以查看返回“users”的查询结果是否包含对地址和电话的引用。

我尝试过仅使用用户和地址使用 2 个表,结果正常。

现在我添加了“电话”表,这是第三个表,然后我收到如下所示的错误。这真的是连接 3 个或更多表的正确方法吗?

测试代码

      try {
//get entity manager
String WEB_PU = "NoJSFPU";
EntityManagerFactory factory = Persistence.createEntityManagerFactory(WEB_PU);
EntityManager em = factory.createEntityManager();

//run query
List<Users> usersList = em.createQuery("SELECT u FROM Users u").getResultList();

//loop to print out each result
for(Users item : usersList) {
//display user info
System.out.println(item.getId() + " " + item.getFirstname());

List<Addresses> addrs = item.getAddresses();
for(Addresses ad : addrs) {
//display address info
System.out.println("Address:::" + ad.getLocation());

List<Phone> pho = ad.getPhone();
for(Phone p : pho) {
//display phone info
System.out.println("phone#" + p.getNumber());
}

}//end inner for
}//end outer for
System.out.println("==========================");

}
catch(Exception e) {
System.out.println("seriously wtf: " + e.toString());
System.exit(1);
}

错误

Exception Description: predeploy for PersistenceUnit [NoJSFPU] failed.
Internal Exception: Exception [TOPLINK-7250] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: [class local.test.session.Addresses] uses a non-entity [class local.test.session.Phone] as target entity in the relationship attribute [private java.util.List local.test.session.Addresses.phone].

最佳答案

我明白了。必须使用@JoinTable注释来指定。

现在如果我运行测试代码,就可以获得所有3个表的数据:D

地址

@ManyToOne
@JoinTable(name = "Addresses", joinColumns = {@JoinColumn(name="user_id",
referencedColumnName = "user_id") } )
private Users user;

电话

@ManyToOne
@JoinTable(name = "Phone", joinColumns = {@JoinColumn(name="address_id",
referencedColumnName = "address_id") } )
private Addresses address;

关于java - 为什么无法使用 JPA TopLink 注释连接第三个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4446690/

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