2012-05-30 131 views
0

我已經定義了一組表T1,T2的複雜關係@OneToMany,... TN:JPA:定義

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註解來定義這種關係,或者我應該注入(如何?)的的EntityManager中的每個實例T1並調用@NamedQuery?

回答

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; 
} 
+0

好吧,據我所知,我需要爲我的'N'表創建'N'類。謝謝。 – Pierre

2

我想你應該使用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/