简体   繁体   中英

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 idUser 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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM