Hibernate继承映射方式一

继承映射方式一:一个子类一张表 ,一张表对应一个配置文件

场景:父类person,子类student、teacher

Person.java

package com.fgh.hibernate;

public class Person {

	private String id;

	private String name;

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

Student.java

package com.fgh.hibernate;

public class Student extends Person {

	private String cardId;

	public String getCardId() {
		return cardId;
	}

	public void setCardId(String cardId) {
		this.cardId = cardId;
	}

}

Teacher.java

package com.fgh.hibernate;

public class Teacher extends Person {

	private int salary;

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

}

Student.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="com.fgh.hibernate.Student" table="student_extend">

		<id name="id" column="id" type="string">
			<generator class="uuid"></generator>
		</id>

		<property name="name" column="name" type="string"></property>
		<property name="cardId" type="string"></property>
	</class>
</hibernate-mapping>

Teacher.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="com.fgh.hibernate.Teacher" table="teacher_extend">

		<id name="id" column="id" type="string">
			<generator class="uuid"></generator>
		</id>
		<property name="name" type="string"></property>
		<property name="salary" type="int"></property>
	</class>
</hibernate-mapping>
测试类:

package com.fgh.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class ExtendMappingTest {

	private static SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Session session = sessionFactory.openSession();
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Student student = new Student();
			student.setName("zhangsan");
			student.setCardId("213421342");

			Teacher teacher = new Teacher();
			teacher.setName("lilaoshi");
			teacher.setSalary(4000);

			session.save(student);
			session.save(teacher);

			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			if (null != tx) {
				tx.rollback();
			}
		} finally {
			session.close();
		}
	}
}



你可能感兴趣的:(Hibernate)