embeddedId and session.load
I have 3 primary keys like in the following example:
@Entity
class User {
@EmbeddedId
@AttributeOverride(name="firstName", column=@Column(name="fld_firstname")
UserId id;
Integer age;
}
@Embeddable
class UserId implements Serializable {
String firstName;
String lastName;
String idUser;
}
in my application when I run session.load(persistenceClass,idClass) it should return the user that its idU开发者_如何学JAVAser is idClass. (I know that it's not trivial but the the id of the user is unique and the first name and last name are primary key as well since there can't be more than one user with the same username and password).
How can I do it without customizing for each class an SQL Query?
You should not embed firstName and lastName in the primary key. userId should be your primary key, and you should add a unique constraint on [firstName, lastName]. BTW, putting these additional fields in the primary key only guarantees that [idUser, firstName, lastName] is unique, but you might still have two users with different idUsers, but with the same [firstName, lastName].
Now to answer the original question, I don't see where the problem is :
UserId userId = new UserId("theId", "theFirstName", "theLastName");
User user = (User) session.load(User.class, userId);
If you don't actually need a composite key, perhaps it would be better to use @UniqueContraint
to ensure uniqueness:
@Entity
@Table(uniqueConstraints =
@UniqueConstraint(columnNames = {"idUser", "fld_firstName", "lastName"}))
class User {
@Id
String idUser;
@Column(name="fld_firstname")
String firstName;
String lastName;
Integer age;
}
精彩评论