我需要选择哪种关系?

时间:2014-07-15 21:51:32

标签: java hibernate

我目前正在研究Hibernate(使用Spring,如果重要的话),我尝试创建一个小型Web应用程序,其中有人可以注册并登录。有一个受Spring Security和我保护的安全区域已经让UserDetailsService工作了,所以Spring Security正在使用Hibernate的东西来登录。

现在我正在为新用户注册。我想到了如何做到这一点,我开始为激活提供一个单独的表,基本上有3列:activationIdusernameactivation_code。激活码将是某种哈希值,但我想它与此问题无关。

我的问题基本上是,如何处理我的users表和activations之间的关系。我需要将username中的activationsusername表格中的users相关联。

我是否必须使用一对一映射?或者如何将另一个表中的一列完全链接到激活表中?

这是我的User实体:

@Entity
@Table(name = "users")
public class User {

    @Id
    @Column(name = "username", unique = true, nullable = false, length = 45)
    private String username;
    @Column(name = "password", nullable = false, length = 64)
    private String password;
    @Column(name = "enabled", nullable = false)
    private boolean enabled;
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
    private Set<UserRole> userRole = new HashSet<UserRole>(0);
    @Column(name = "name")
    private String name;
    @Column(name = "lastname")
    private String lastname;

    public User() {
    }

    public User(String username, String password, boolean enabled) {
        this.username = username;
        this.password = password;
        this.enabled = enabled;
    }

    public User(String username, String password, boolean enabled, Set<UserRole> userRole) {
        this.username = username;
        this.password = password;
        this.enabled = enabled;
        this.userRole = userRole;
    }

    // Getters and setters for all attributes omitted 

}

如果您还需要UserRole实体,请告诉我,我会添加它,但我认为不需要它。这也是我UserActivation实体的当前版本,但当然还没有完成:

import javax.persistence.*;

@Entity
@Table(name = "activations")
public class UserActivation {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long activationId;
    @Column(length = 64)
    private String activationCode;
    @Column
    private String userName; // here we need some magic relationship
}

1 个答案:

答案 0 :(得分:0)

您可以使用ManyToOne映射:

@Entity
@Table(name = "activations")
public class UserActivation {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long activationId;
    @Column(length = 64)
    private String activationCode;

    @ManyToOne(optional=false)
    @JoinColumn(name="USER_NAME")
    private User user; // since your User Id is username, the join column will be username
}

如果您希望用户名是唯一的,则意味着对单个用户进行一次激活:

@Entity
@Table(name = "activations",uniqueConstraints=@UniqueConstraint(columnsnames="USER_NAME"))