为什么不能使用JPA TopLink注释加入第3个表?

时间:2010-12-15 04:28:02

标签: java jpa join toplink

我有简单的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张表,然后我收到错误,如下所示。 这是加入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].

1 个答案:

答案 0 :(得分:1)

我发现了。必须使用@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;