1
package com.sm.hibernate.pojo;
import java.util.Set;
public class User {
private int id;
private String name;
private int qq;
private Grade grade;
private Set<Course> courses;
public Set<Course> getCourses() {
return courses;
}
public void setCourses(Set<Course> courses) {
this.courses = courses;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQq() {
return qq;
}
public void setQq(int qq) {
this.qq = qq;
}
}
此处最最重要的两点 ,一个是鉴别器,一个是子类声明,缺一不可
<?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 package="com.sm.hibernate.pojo">
<class name="User" table="hib_user">
<id name="id">
<generator class="native"></generator>
</id>
<discriminator column="type" type="string"/>
<property name="name"></property>
<property name ="qq"></property>
<many-to-one name = "grade" cascade="all" column="gradeid" class ="Grade">
</many-to-one>
<set name="courses" table="hib_uc">
<key column="userid"></key>
<many-to-many column="courseid" class="Course"></many-to-many>
</set>
<subclass name="Guest" discriminator-value="guest">
<property name="email"/>
</subclass>
</class>
</hibernate-mapping>
2
继承类
package com.sm.hibernate.pojo;
public class Guest extends User{
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
他没有 映射文件
3 把原来表删除了再执行
4
package com.sm.hibernate.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.sm.hibernate.pojo.Grade;
import com.sm.hibernate.pojo.Guest;
import com.sm.hibernate.pojo.User;
public class Test4 {
public static void main(String[] args) {
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
Guest guest = new Guest();
guest.setName("hello");
guest.setEmail("emial");
session.save(guest);
session.getTransaction().commit();
session.close();
}
}
5 结果