每棵继承树映射成一张表
测试代码:
public void testSave1() { Session session = null; try { session = HibernateUtils.getSession(); session.beginTransaction(); Pig pig = new Pig(); pig.setName("猪"); pig.setSex(true); pig.setWeight(100); session.save(pig); Bird bird = new Bird(); bird.setName("鸟"); bird.setSex(false); bird.setHeight(50); session.save(bird); session.getTransaction().commit(); }catch(Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally { HibernateUtils.closeSession(session); } } /** * 采用load,通过Pig查询 */ public void testLoad1() { Session session = null; try { session = HibernateUtils.getSession(); session.beginTransaction(); Pig pig = (Pig)session.load(Pig.class, 1); System.out.println(pig.getName()); session.getTransaction().commit(); }catch(Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally { HibernateUtils.closeSession(session); } } /** * 采用load,通过Animal查询 */ public void testLoad2() { Session session = null; try { session = HibernateUtils.getSession(); session.beginTransaction(); Animal animal = (Animal)session.load(Animal.class, 1); System.out.println(animal.getName()); session.getTransaction().commit(); }catch(Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally { HibernateUtils.closeSession(session); } } /** * 采用load,通过Animal查询 */ public void testLoad3() { Session session = null; try { session = HibernateUtils.getSession(); session.beginTransaction(); Animal animal = (Animal)session.load(Animal.class, 1); //因为load默认只是lazy,因为我们看到的是Animal的代理对象 //所以通过instanceof是反应不出正真的对象类型的 //因此load在默认情况下是不支持多态查询的 if (animal instanceof Pig) { System.out.println(animal.getName()); }else { System.out.println("不是猪"); } session.getTransaction().commit(); }catch(Exception e) { e.printStackTrace(); session.getTransaction().rollback(); }finally { HibernateUtils.closeSession(session); } }
原文地址:http://liuyj.blog.51cto.com/2340749/1693485