基础配置
persistence.xml
首先应在src目录中新建META-INF文件夹,将persistence.xml文件放入
persistence.xml内容
首先来讲一下单表继承
假设这里有三个实体类
person
| |
teacher student
person俩属性 id 和name
teacher多出一个属性 tittle(职称) student多出一个属性score(分数)
那么在数据库中用表怎么表示这种继承关系呢
一种办法是 一个表中包含所有字段
根据特有字段值生成特定子类
为了方便判断子类类型 增加一个类型字段 指定对象类型
org.hibernate.jpa.HibernatePersistenceProvider
entity.Person
entity.Student
entity.Teacher
另外自己xml方式配置太多,老想继续配置hibernate.cfg.xml
其实从上面persistence.xml需要配置数据库属性就会发现二者是相同的作用的 所以这里hibernate.cfg.xml并不需要再做配置,没要也无妨。
single_table
实体类
Person.java
package entity;
import javax.persistence.*;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="discriminator",discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("person")
public class Person {
private int id;
private String name;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
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;
}
}
@Entity
表示持久化的实体类
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
指定继承类型为单表继承
@DiscriminatorColumn(name="discriminator",discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("person")
Teacher.java
package entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("teacher")
public class Teacher extends Person{
private String tittle;
public String getTittle() {
return tittle;
}
public void setTittle(String tittle) {
this.tittle = tittle;
}
}
Student.java
package entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("student")
public class Student extends Person {
private int score;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
测试类
package test.entity;
import entity.Person;
import entity.Student;
import entity.Teacher;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import static javax.persistence.Persistence.*;
public class hibernateExTest {
public static void main(String args[]){
EntityManagerFactory factory = createEntityManagerFactory("JPA");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Person p =new Person();
p.setName("温丛晓");
Teacher t = new Teacher();
t.setTittle("高级");
t.setName("t1");
Student s = new Student();
s.setScore(100);
s.setName("s1");
em.persist(p);
em.persist(t);
em.persist(s);
em.getTransaction().commit();
em.close();
factory.close();
}
}