hibernate继承映射2

       上一篇博客的继承映射所用到的节点是joined-subclass节点,在数据库端生成的是三个表,而该篇所用到的节点是union-subclass节点,生成的表只有两个。但此种方法生成的表的主键不能进行自增长。

1、创建实体类Animal.java

package cn.itcast.b;

public class Animal {
	private String id;
	private String name;

	public String getName() {
		return name;
	}

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

	public String getId() {
		return id;
	}

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

2、创建实体类Cat.java继承于Animal类

package cn.itcast.b;

public class Cat extends Animal{
	private String catchMouse;

	public String getCatchMouse() {
		return catchMouse;
	}

	public void setCatchMouse(String catchMouse) {
		this.catchMouse = catchMouse;
	}

	
	
}


3、创建实体类Monkey.java继承于Animal类

package cn.itcast.b;

public class Monkey extends Animal{
	private String eatBanana;

	public String getEatBanana() {
		return eatBanana;
	}

	public void setEatBanana(String eatBanana) {
		this.eatBanana = eatBanana;
	}
	
}

4、配置Aminal.hbm.xml





	
	
	
		
			
		
		
		
		
		
			
		
		
		
			
			
	


5、配置hibernate.cfg.xml




	
		true
		
		com.mysql.jdbc.Driver
		jdbc:mysql:///employee
		root
		123456
		org.hibernate.dialect.MySQL5Dialect
		
		
		true
				
		true
		
		update
		
		
	

6、创建测试类App.java

package cn.itcast.b;

import static org.junit.Assert.*;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class App {
	private static SessionFactory sf;
	static {
		sf=new Configuration().configure().buildSessionFactory();
	}
	@Test
	public void test() {
		Session session=sf.openSession();
		session.beginTransaction();
		
		Cat cat = new Cat();
		cat.setName("小猫");
		cat.setCatchMouse("抓猫");
		
		Monkey monkey = new Monkey();
		monkey.setName("猴子");
		monkey.setEatBanana("吃香蕉");
		
		session.save(monkey);
		session.save(cat);
		
		session.getTransaction().commit();
		session.close();
	}

}


你可能感兴趣的:(hibernate)