我有简单的 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 中创建了一些测试数据并尝试运行测试以查看返回“用户”的查询结果是否包含对地址和电话的引用。
我已经尝试仅使用用户和地址使用 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].