单表策略hibernate中的继承

时间:2015-03-02 16:46:35

标签: java hibernate

我将使用三个简单的PersonTeacherStudent类在hibernate中进行简单的继承。

这是我的父类(Person.java

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "Person Type" , discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue(value = "Person")
public class Person implements Serializable {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private String address;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

我的Teacher.java班级:

@Entity
@DiscriminatorValue(value = "Teacher")
public class Teacher extends Person implements Serializable {

    private String teacherDegree;

    public String getTeacherDegree() {
        return teacherDegree;
    }

    public void setTeacherDegree(String teacherDegree) {
        this.teacherDegree = teacherDegree;
    }
}

我的Student.java课程:

@Entity
@DiscriminatorValue(value = "Student")
public class Student extends Person implements Serializable {

    private String studentCollege;

    public String getStudentCollege() {
        return studentCollege;
    }

    public void setStudentCollege(String studentCollege) {
        this.studentCollege = studentCollege;
    }
}

Hibernate配置:

...
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="com.abc.Person"/>
        <mapping class="com.abc.Teacher"/>
        <mapping class="com.abc.Student"/>
...

测试员类:

    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();

    Teacher teacher2 = new Teacher();

    teacher2.setName("Teacher ABC"); // person property
    teacher2.setAddress("NewYork"); // person property
    teacher2.setTeacherDegree("phd"); // teacher property

    session.save(teacher2);

    session.getTransaction().commit();
    session.close();

但我收到了这个错误:

ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Type) values ('NewYork', 'Teacher ABC', 'phd', 'Teacher')' at line 1

1 个答案:

答案 0 :(得分:0)

同样作为约定,您应该使用以下样式。我不记得此刻,但我认为你需要某种类型的转义为列名称中的空格。

@DiscriminatorColumn(name = "PERSON_TYPE" , discriminatorType = DiscriminatorType.STRING)

有时它会让生活更容易遵守社区的大部分编码习惯。