我定义了一组表 t1、t2、... tN:
mysql> desc t1;
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
(...)
+-------------+------------------+------+-----+---------+----------------+
(...)
mysql> desc tN;
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
(...)
+-------------+------------------+------+-----+---------+----------------+
以及一个表,该表将存储有关表 t1, ... tN 中每条记录的一些注释:
mysql> desc postit;
+---------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| foreign_id | int(10) unsigned | NO | MUL | NULL | |
| foreign_table | varchar(20) | NO | MUL | NULL | |
| content | text | NO | | NULL | |
(....)
+---------------+------------------+------+-----+---------+----------------+
现在我应该如何为表“t1”定义 @Entity ....
@Entity(name="T1")
@Table(name="t1")
public class T1
{
(...)
public List<PostIt> getComments() { ... }
}
从表“postit”中检索其所有评论,如表达式所示
select P from postit as P where P.foreign_table="t1" and P.foreign_id= :t1_id
是否有特定的 JPA 注释来定义此关系,或者我应该在 T1 的每个实例中注入(inject)(如何?) EntityManager 并调用 @NamedQuery ?
最佳答案
我认为你应该使用 inheritance 为表建模.
这样你就有了 AbstractTable
@Entity
@DiscriminatorColumn(name="type_id")
@DiscriminatorValue("-1")
...
class AbstractTable {
@OneToMany(mappedBy="foreign_id")
public List<PostIt> getComments() { ... }
}
...
}
还有:
@Entity
@DiscriminatorValue("1")
...
class Table1 {}
@Entity
@DiscriminatorValue("2")
...
class Table2 {}
如果您需要双向关系,那么您需要弄清楚如何从 Postit 实体引用表。我认为类似
@ManyToOne
public AbstractTable getTable() { ... }
应该可以。
更多信息可以在这里找到http://wleeper.com/2009/12/17/jpa-onetomany-with-inheritance/
关于java - JPA : defining a complex @OneToMany relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10813448/