以many-to-many為例,有Position和User兩張表,一個(gè)Position可以有多個(gè)Users,一個(gè)User也可以有多個(gè)Position,中間的關(guān)聯(lián)表為 test_user_position 。通過在PO中加入XDoclet,自動生成hbm配置文件。不廢話,看代碼。
Position.java
package test;

import java.util.Set;
import java.util.TreeSet;

/** *//**
* @hibernate.class table="test_position"
*/
public class Position
{

private int id;

private int name;

private Set<Users> users = new TreeSet<Users>();

/** *//**
* @hibernate.id generator-class="identity" type="int"
*/
public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

/** *//**
* @hibernate.property length="25"
*/
public int getName()
{
return name;
}

public void setName(int name)
{
this.name = name;
}

/** *//**
* @hibernate.set inverse="true" lazy="true" table="test_user_position"
* @hibernate.collection-key column="position_id"
* @hibernate.collection-many-to-many class="test.Users" column="user_id"
*/
public Set<Users> getUsers()
{
return users;
}

public void setUsers(Set<Users> users)
{
this.users = users;
}
}
接下來是Users.java
package test;

import java.util.*;

/** *//**
* @hibernate.class table="test_uses"
*/
public class Users
{

private int id;

private String name;

private Set<Position> positions = new TreeSet<Position>();

/** *//**
* @hibernate.id generator-class="identity" typ="int"
*/
public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

/** *//**
* @hibernate.property length="25"
*/
public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

/** *//**
* @hibernate.set table="test_user_position" lazy="true"
* @hibernate.collection-key column="user_id"
* @hibernate.collection-many-to-many class="test.Position" column="position_id"
*/
public Set<Position> getPositions()
{
return positions;
}

public void setPositions(Set<Position> positions)
{
this.positions = positions;
}
}
Position.java


























































接下來是Users.java

























































在Myeclipse中右鍵點(diǎn)擊項(xiàng)目,選擇“Properties",從界面中選擇”Myeclipse/XDoclet",點(diǎn)擊“Add Standard...”,添加“Standard Hibernate”,點(diǎn)擊OK,結(jié)束設(shè)置。
在項(xiàng)目中建立Hibernate.cfg.xml,配置好SessionFactory和數(shù)據(jù)源
右鍵點(diǎn)擊項(xiàng)目,選擇“Myeclipse/Run XDoclet",將自動創(chuàng)建以上兩個(gè)類對應(yīng)的hbm文件。
注意:創(chuàng)建完成的hbm文件存在問題,里面有role和readonly屬性,將前者改為name,后者刪掉即可。
轉(zhuǎn)自:http://www.aygfsteel.com/xmllong/archive/2008/07/31/218938.html