我是JPA的新手,在我看来,JoinColumn的行为有所不同,我想知道为什么。
UserEntites应该加入权限。
组织应加入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-并按预期工作。
情况二
参见我的另外两个班:
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;
}
组织设置:
@Entity
@Table(name = "organization_settings")
public class OrganizationSettingsEntity {
@Id
private Long organizationId;
}
如您所见->组织正在使用名称为id的Organizationing Joining OrganizationSettings进行工作。但是,在OrganizationSettings中没有ID-只有OrganizationId。这行得通-但让我感到奇怪。
为什么第二个也起作用?不是@JoinColumn(name="organizationId")
吗?
春天与它无关。JPA是标准API。
1-N情况:您将在authorities
表中创建一个名称为FK的列userId
(链接回users
表)。您似乎还希望对userId
元素中的该字段重新使用同一列...这将迟早引起您的问题,因为重新使用未标记该userId
字段的列insertable=false, updatable=false
将意味着两者都可能尝试对其进行更新。要么删除userId
元素中的字段,要么将该字段转换为类型UserEntity
(并mappedBy
在1-N所有者字段上使用,使其具有双向关系),或者userId
使用前面提到的那些属性标记该字段。
1-1情况:您将在organization
表中创建一个名称为FK的列id
(链接到该organization_settings
表)。遗憾的是,该列与该表的PK将使用的列相同,因此您再次出于两个不同的目的重用该列,将导致地狱。将关系FK的列更改为不同的内容-FK在organization
表中,而不是在另一侧。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句