2016-11-11 87 views
0

我是JPA的新手,在我看來JoinColumn行爲不同,我想知道爲什麼。春季數據的奇怪行爲jpa

UserEntites應該加入authorites。

組織應加入OrganizationSettings。

我有兩種不同的方法,兩者都有效。

案例1

UserEntity:

@Entity 
@Table(name = "users") 
@Inheritance(strategy = InheritanceType.JOINED) 
public class UserEntity { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id; 

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) 
    @JoinColumn(name = "userId") 
    private List<UserAuthority> authorities; 
} 

UserAuthoritiesEntity

@Entity(name = "authorities") 
@Table(name = "authorities") 
public class UserAuthority { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id; 

    private Long userId; 

    private String authority; 
} 

在這裏,在我看來JoinColumn名稱引用UserAuthority.userId - 和它的作品如預期。

案例2

見我的其他兩個類:

OrganizationEntity:

@Entity 
@Table(name="organization") 
public class OrganizationEntity { 

    @Id 
    @GeneratedValue(strategy= GenerationType.IDENTITY) 
    private Long id; 

    @NotNull 
    private String url; 

    @NotNull 
    private String name; 

    @OneToOne (cascade = CascadeType.ALL,fetch = FetchType.EAGER) 
    @JoinColumn(name="id",updatable = false) 
    private OrganizationSettingsEntity settings; 
} 

OrganizationSettings:

@Entity 
@Table(name = "organization_settings") 
public class OrganizationSettingsEntity { 

    @Id 
    private Long organizationId; 
} 

正如你可以在這裏看到 - >組織的加盟使用OrganizationSettings名稱ID - 哪些工作。但是在OrganizationSettings中沒有id - 只是organizationId。這工作 - 但讓我感到驚訝。

爲什麼第二個也有效?不應該是@JoinColumn(name="organizationId")

回答

2

春天與它無關。 JPA是一個標準的API。

1-N的情況:你會在authorities表名userId(鏈接回users表)創建FK列。您似乎也想重新使用該元素中此userId字段的同一列...這會稍後導致您的問題,因爲重新使用列時沒有將userId字段標記爲insertable=false, updatable=false,這意味着兩者都可能會嘗試更新它。要麼刪除元素中的userId字段,要麼將字段轉換爲UserEntity類型(並將其作爲雙向關係,在1-N所有者字段中使用mappedBy),或者使用前面提及的屬性標記userId字段。

1-1案例:您將在organization表中創建一個名爲id(鏈接到organization_settings表)的FK列。可悲的是,這是與該表的PK將要使用的列相同的列,因此您再次將該列用於2個不同的目的,並將導致地獄。將關係FK的列更改爲不同的內容 - FK位於organization表中,而不是另一側。

+0

謝謝@neil - 但我覺得它有點奇怪的1-1案例。 當我通常建立我的MySQL表(沒有JPA)時,例如,我在用戶中使用了id作爲PK,然後在擴展表中 - 比如user_mentors - user_id。 這在我看來很標準。 你能告訴我該怎麼做一些小小的代碼 - 那麼也許我明白了:) –

+0

你的意思是一個*連接表*? 1-1不使用連接表。 1-N **可以使用連接表(如果將其配置爲)。請參閱http://www.datanucleus.org/products/accessplatform_5_0/jpa/orm/one_to_many_collection.html中的1-N和http://www.datanucleus.org/products/accessplatform_5_0/jpa/orm/one_to_one中的1-1 .html這些都是在JPA標準中。它爲你選擇合適的映射來獲得你想要達到的目標(你還沒有明確) –

+0

同意:)我沒有說清楚。 好的 - 所以1-1案件持有settings_id而organization_settings只有一個PK ID?你是這個意思嗎? –