0

我已经定义了一组表 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 的每个实例中注入(如何?)一个EntityManager并调用 @NamedQuery ?

4

2 回答 2

2

我认为您应该使用继承对表进行建模。

这样你就有了 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/

于 2012-05-30T11:47:13.007 回答
1

您的设计对应于继承树,其中根 AbstractComment 实体的所有子类都将存储在同一个表中,使用鉴别器列 ( foreign_table):

@Entity
@Table(name = "postit")
@Inheritance(strategy = SINGLE_TABLE)
@DiscriminatorColumn(name = "foreign_table", discriminatorType = STRING)
public abstract class AbstractComment {
    // ... fields, getters, setters
}

@Entity
@DiscriminatorValue("t1")
public class T1Comment extends AbstractComment {

}

@Entity
@Table(name="t1")
public class T1 {
    @OneToMany
    @JoinColumn(name = "foreign_id")
    private Set<T1Comment> comments;
}
于 2012-05-30T11:48:53.120 回答