gpt4 book ai didi

java - hibernate中的单表策略继承

转载 作者:太空宇宙 更新时间:2023-11-04 14:06:28 24 4
gpt4 key购买 nike

我将使用三个简单的 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

最佳答案

作为惯例,您应该采用以下样式。我现在不记得了,但我认为您需要对列名称中的空格进行某种转义。

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

有时,遵守社区的大多数编码习惯会让生活变得更轻松。

关于java - hibernate中的单表策略继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28815091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com