hibernate详解(2)->>继承关系映射(一)
hibernate详解(二)----继承关系映射(一)? package com.zxf.domain/** 歌手抽象类 */public abstract cl
hibernate详解(二)---->>继承关系映射(一)
?
package com.zxf.domain;/** 歌手抽象类 */public abstract class Singer {private Long id; //对象标识符(OID)private String name; //名称private String region; //歌手所属区域(如:华人、日韩、欧美等)private String description; //描述public Singer(){} //无参数的构造方法//以下为所有属性的getters和setters方法...}?
SingleSinger.java
?
? package com.zxf.domain;/** 单人歌手实体类 */public class SingleSinger extends Singer {private Character gender; //性别public SingleSinger(){} //无参数的构造方法//以下为所有属性的getters和setters方法...}?
Bands.java
?
? package com.qiujy.domain;/** 乐队组合实体类 */public class Bands extends Singer {private String leader; //主唱姓名public Bands(){} //无参数的构造方法//以下为所有属性的getters和setters方法...}?
Singer.hbm.xml
?
? ?配置文件? hibernate.cfg.xml
?
? ?
下面写一个测试类来测试一下:
?
SingerTest.java
?
? import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import com.zxf.domain.Bands;import com.zxf.domain.Singer;import com.zxf.domain.SingleSinger;/** * 继承映射测试 * @author z_xiaofei168 */public class SingerTest {@SuppressWarnings("unchecked")public static void main(String[] args) {//根据hibernate的默认配置文件构建一个SessoinFactory实例SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); testAdd(sessionFactory);testQuery(sessionFactory);}public static void testAdd(SessionFactory sessionFactory) {//获取Session实例Session session = sessionFactory.openSession();//开启事务session.beginTransaction();SingleSinger singer = new SingleSinger();singer.setName("周杰棍");singer.setRegion("华人");singer.setDescription("大舌头");singer.setGender('男');session.save(singer);Bands bands = new Bands();bands.setName("花朵乐队");bands.setRegion("日韩");bands.setDescription("以口水歌为主");bands.setLeader("大伟");session.save(bands);//提交事务session.getTransaction().commit(); //关闭Sessionsession.close();}public static void testQuery(SessionFactory sessionFactory) {//获取Session实例Session session = sessionFactory.openSession();//开启事务session.beginTransaction();List<Singer> singers = session.createQuery("from Singer").list();for (Singer singer2 : singers) {if(singer2 instanceof SingleSinger){SingleSinger ss = (SingleSinger)singer2;System.out.println("是单人歌手:" + ss.getName() + ",性别:" + ss.getGender());}else if(singer2 instanceof Bands){Bands ban = (Bands)singer2;System.out.println("是乐队组合:" + ban.getName() + ",主唱:" + ban.getLeader());}}//提交事务session.getTransaction().commit(); //关闭Sessionsession.close();}}?
?
程序的运行结果如下所示:
?
?
?
?
<script type="text/javascript"></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>