假设我们有两个表,user
并且domain
. 用户可能有一个域,一个域可能有多个用户。所以我们将做单向多对一:
@Entity
@Table(name = "DOMAIN")
public class Domain implements Serializable
{
@Id
@Column(name = "DOMAIN_ID")
private Integer domainId;
@Column(name = "NAME")
private String domainName;
}
@Entity
@Table(name = "\"USER\"")
public class User implements Serializable
{
@Id
@GeneratedValue(generator = "USER_SEQ")
@GenericGenerator(name = "USER_SEQ", strategy = "sequence", parameters = @Parameter(name = "sequence", value = "SEQ_USER_ID"))
@Column(name = "USER_ID", nullable = false)
private Long userId;
@Column(name = "FIRST_NAME")
private String firstName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "DOMAIN_ID")
@ForeignKey(name = "DOMAIN_ID")
private Domain domain;
}
Domain
表是不变的东西,字典。虽然User
是可编辑的表。
我正在创建一个基本表单,用户选择将在其中创建新用户的域。假设我的控制器收到了这些数据:
Integer domainId = 1;
String firstName = "aaa";
所以我正在创建新用户:
User newUser = new User();
newUser.setFirstName( firstName );
现在我的问题来了,我应该这样做吗?
Domain domain = somthingThatWillFetchObjectFromDb.getDomain( domainId );
newUser.setDomain( domain );
//save user
这将生成额外的选择,以获取域。当然我可以用Integer domainId
POJO 代替,但那不是 ORM。那么问题又来了,这是应该做的吗?