2012-10-06 32 views
0

我有以下表,從here拍攝(如Spring Security的模型的一部分):創建休眠mappings-初學者QN

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); 

我真正的新hiberanate,我不知道如何映射這些表到休眠xml文件中的映射。如何映射外鍵?如何映射索引?我知道每個表都有一個主鍵,但在這種情況下,權限表不會。那麼這意味着hibernate映射中沒有<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> 

任何想法,我做錯了嗎?謝謝!

+0

你能告訴你的bean結構? – RAS

回答

0

我會推薦使用Annotations而不是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/

塞巴斯蒂安