Let’s say we have two tables, user and domain. User may have one Domain, one Domain may be for many users. So we will do unidirectional many to one:
@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 table is something unchangable, dictionary. While User is editable table.
I’m creating a basic form where user selects domain in which new user will be created. Lets say that my controller received those data:
Integer domainId = 1;
String firstName = "aaa";
So I’m creating new user:
User newUser = new User();
newUser.setFirstName( firstName );
Now comes my question, should I do this way?
Domain domain = somthingThatWillFetchObjectFromDb.getDomain( domainId );
newUser.setDomain( domain );
//save user
THis will generate additional select, to fetch domain. Of course I can use Integer domainId instead of POJO, but that’s not ORM. So once again the question, is this the way it should be done?
Yes, that’s what you should do. If you don’t want to actually load the domain information from the database, use the strangely named
Session.load()method instead of theSession.get()method. If the domain is not already loaded into the session,Session.load()will simply return you an unitialized entity proxy for the domain (just like if you had loaded some entity with a lazy association to the domain), without hitting the database.That said, if domain is unchangeable, why do you set
@Cascade(CascadeType.ALL)on the domain field? This means that every time you’re merging or updating a user, the domain will also be merged or updated. And even worse: if you delete a user, the domain will also be deleted (which of course will lead to an exception if other users are referencing the same domain).