简体   繁体   English

EmbeddedId和session.load

[英]embeddedId and session.load

I have 3 primary keys like in the following example: 我有3个主键,如以下示例所示:

@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. 在我的应用程序中,当我运行session.load(persistenceClass,idClass)时,应返回其idUser为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). (我知道这并非易事,但用户的ID是唯一的,名字和姓氏也是主键,因为不能有多个用户使用相同的用户名和密码)。

How can I do it without customizing for each class an SQL Query? 如何在不为每个类自定义SQL查询的情况下做到这一点?

You should not embed firstName and lastName in the primary key. 您不应在主键中嵌入firstName和lastName。 userId should be your primary key, and you should add a unique constraint on [firstName, lastName]. userId应该是您的主键,并且应该在[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]. 顺便说一句,将这些附加字段放在主键中只能保证[idUser,firstName,lastName]是唯一的,但是您可能仍然有两个用户具有不同的idUser,但具有相同的[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: 如果您实际上不需要复合键,则最好使用@UniqueContraint来确保唯一性:

@Entity
@Table(uniqueConstraints = 
    @UniqueConstraint(columnNames = {"idUser", "fld_firstName", "lastName"}))
class User {   
    @Id
    String idUser;

    @Column(name="fld_firstname")
    String firstName;       
    String lastName;       
    Integer age; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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