集合属性映射
即持久化类的某些属性为集合类型,并且该属性不属于其他持久化类。
1.List 集合属性
①在POJO类添加属性 (还有setter getter方法!)
注:此处应 用接口声明 属性,且以具体实现类完成初始化(否则会出现NullPointerException)
//添加集合属性skill
private List<String> skill = new ArrayList<String>();
②映射文件 增加list元素
<!--name指定 配置的属性 -->
<list name="skill" table="skill">
<!--指定对应外键列名字 -->
<key column="heroId" not-null="true"/>
<!--指定索引列名字 -->
<list-index column="list_num"/>
<!--指定存储该属性的对应的列名 -->
<element column="skill" type="string"/>
</list>
③测试类
Hero n = new Hero();
n.setName("卫宫");
n.setWeapon("干将莫邪");
//集合属性需要另外建立 再存回持久化类
List<String> skills = new ArrayList<String>();
skills.add("固有结界");
n.setSkill(skills)
2.数组属性
①在pojo类添加属性(setter getter)
private String[]skill;
②映射文件 增加array元素
<array name="skill" table="skill_array">
<!--指定对应外键列名字 -->
<key column="heroId" not-null="true"/>
<!--指定索引列名字 -->
<list-index column="list_num"/>
<!--指定存储该属性的对应的列名 -->
<element column="skill" type="string"/>
</array>
③测试类
Hero n = new Hero();
n.setName("saber");
n.setWeapon("Excalibur");
//集合属性需要另外建立 再存回持久化类
String[] skill = new String[]{"风王结界","誓约胜利之剑","远离尘世的理想乡"};
n.setSkill(skill);
3.set属性
①pojo
//用接口声明 并 以具体实现类完成初始化
private Set<String> skill = new HashSet<String>();
②映射配置
<!--name指定 配置的属性 -->
<set name="skill" table="skil_set">
<key column="hero_id" not-null="true"/>
<element type="string" column="skill" not-null="true"/>
</set>
4.map属性
①pojo
//用接口声明 并 以具体实现类完成初始化
private Map<String,Integer> skill = new HashMap<String,Integer>();
②映射配置
<map name="skill" table="skill_map">
<!-- 外键映射 -->
<key column="hero_id" not-null="true"/>
<!--map key -->
<map-key column="skill" type="string"/>
<!--map value -->
<element column="mana" type="int"/>
</map>
5.bag属性
①pojo bag能映射List,set,collecrion属性
private Collection<String> skill = new ArrayList<String>();
②映射配置
<bag name="skill" table="skill_bag">
<key column="hero_id" not-null="true"/>
<element column="skill" type="string" />
</bag>