Bag是集合,与Set不同的是,Bag允许重复的元素,
在Java的标准API中并没有提供Bag容器,Hibernate提供自己的Bag实现,允许您将List映射为Bag。
您可以如下定义User类别,其中的List成员将被用作Bag来使用,而不管物件在List容器中的顺序:
package onlyfun.caterpillar;
import java.util.List;
public class User {
private Integer id;
private String name;
private List items;
// 必须要有一个预设的建构方法
// 以使得Hibernate可以使用Constructor.newInstance()建立物件
public User() {}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List getItems() {
return items;
}
public void setItems(List items) {
this.items = items;
}
public void addItem(String item) {
items.add(item);
}
public void removeItem(String name) {
items.remove(name);
}
}
mysql> select * from user; +----+-------------+ | id | name | +----+-------------+ | 1 | caterpillar | | 2 | momor | +----+-------------+ 2 rows in set (0.00 sec) mysql> select * from item; +----+--------------------+ | id | name | +----+-------------------+ | 1 | Java Gossip | | 1 | Java Gossip | | 1 | Caxxx A80 | | 2 | Snoppy world | +----+-------------------+ 4 rows in set (0.00 sec) |
xml 代码
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class name="onlyfun.caterpillar.User" table="user">
- <id name="id" column="id" type="java.lang.Integer">
- <generator class="native" />
- </id>
- <property name="name" column="name" type="java.lang.String" />
- <idbag name="items" table="item">
- <collection-id column="cid" type="java.lang.String">
- <generator class="uuid.hex" />
- </collection-id>
- <key column="id" />
- <element column="name" type="java.lang.String" />
- </idbag>
- </class>
- </hibernate-mapping>
mysql> select * from user; +----+-------------+ | id | name | +----+-------------+ | 1 | caterpillar | | 2 | momor | +----+-------------+ 2 rows in set (0.00 sec) mysql> select * from item; +------------------------------------------------+----+--------------------+ | cid | id | name | +------------------------------------------------+----+--------------------+ | 297eba61056726030105672605df0001 | 1 | Java Gossip | | 297eba61056726030105672605df0002 | 1 | Java Gossip | | 297eba61056726030105672605df0003 | 1 | Caxxx A80 | | 297eba61056726030105672605df0004 | 2 | Snoppy world | +------------------------------------------------+----+-------------------+ 4 rows in set (0.00 sec) |