0

我有以下表格,取自这里(作为 Spring Security 模型的一部分):

  create table users(
      username varchar_ignorecase(50) not null primary key,
      password varchar_ignorecase(50) not null,
      enabled boolean not null);

  create table authorities (
      username varchar_ignorecase(50) not null,
      authority varchar_ignorecase(50) not null,
      constraint fk_authorities_users foreign key(username) references users(username));

  create unique index ix_auth_username on authorities (username,authority);

我对休眠真的很陌生,不知道如何将这些表映射到 xml 文件中的休眠映射。如何映射外键?如何映射索引?我知道每个表都有一个主键,但在这种情况下,权限表没有。所以这意味着<id>休眠映射中没有列?

这是我到目前为止所得到的:

<class name="com.foo.beans.User" table="users">
    <id name="username" column="username"/>
    <property name="password" column="password"/>
    <property name="enabled" column="enabled"/>
</class>

<class name="com.foo.beans.Authority" table="authorities">
    <composite-id name="ix_auth_username">
        <key-property name="username" column="username" />
        <key-property name="authority" column="authority" />
    </composite-id>
</class>

知道我做错了什么吗?谢谢!

4

1 回答 1

0

我建议使用注释而不是 XML。XML 有点过时了。

使用注释它看起来像这样:

@Entity
@Table(name="user_table")
public class User implements Serializable {

    Long userId;
    String username;
    String password;
    boolean enabled;

    @Id
    @Column(name="user_table_id")
    public Long getUserId() { return userId; }

    public void setUserId(Long id) { this.userId = userId; }

    @Column(name="username", length=80, nullable=true)
    public String getUsername() { return username };

    public void setUsername(String username) { this.username = username; };
    /* getters and settings annotated et cetera */
}   

权限很可能是用户对象内的延迟加载列表。

因此,在用户内部,您将定义如下内容:

List<Authority> authorities;

@OneToMany(mappedBy="userId",
               cascade=CascadeType.ALL, 
               fetch=FetchType.LAZY)
@OrderBy("xyz")
public List<Authority> getAuthorities() {
    return authorities;
}

public void setAuthorities (List<Authority> authorities) { this.authorities = authorities; };

有关更多示例和注释选项,请参阅参考指南:http: //docs.jboss.org/hibernate/annotations/3.5/reference/en/html/

塞巴斯蒂安

于 2012-10-09T13:22:10.570 回答