我将使用三个简单的Person
,Teacher
和Student
类在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
答案 0 :(得分:0)
同样作为约定,您应该使用以下样式。我不记得此刻,但我认为你需要某种类型的转义为列名称中的空格。
@DiscriminatorColumn(name = "PERSON_TYPE" , discriminatorType = DiscriminatorType.STRING)
有时它会让生活更容易遵守社区的大部分编码习惯。