使用Hibernate @ManyToOne关系

时间:2017-12-29 05:35:28

标签: java mysql hibernate javafx

被修改

(不完全是How to use @Id with String Type in JPA / Hibernate?的副本)

原因:

  • 当时,我得到的错误是:

    org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String
    ---- many lines below
    at ajfmo.studycontrol.DAO.StudentDAO.createStudent(StudentDAO.java:49)
    

    但这不是我得到的唯一错误,我在评论中提到我在这个操作上度过了一段艰难时期,因为我无法让它工作(初学者)。

  • 即使我目前得到的错误也是由@GeneratedValue注释引起的,这个注释不是必需的,所以我可以摆脱它和许多其他注释。

  • 最重要的是,异常并不相同

    org.hibernate.TypeMismatchException: Provided id of the wrong type. Expected: class java.lang.String got class java.lang.Long
    
  • 我仍然看不到“重复帖子”之间的关系。

您好,谢谢您的时间。

正如标题所说,我需要将数据保存到一个名为“学生”的表中,其中学生有职业和部分,但职业和部门有很多学生。

这是我的数据库图表:

Database diagram

我将发布几乎所有代码,以确保您了解我正在做的事情。 我是自学Hibernate并将其作为一种练习,更好地理解这个工具并提高我的技能和知识。我不明白我正在做的一切,但我想我会走上好路。

这是我的项目结构:

Project structure

这是我需要完成工作的窗口......

Register a student

我从ComboBoxes中选择一个选项,并填写所需的信息,如ID和Name,然后点击Guardar,或者用英语保存。

在这一刻,这是我得到的例外:

org.hibernate.id.IdentifierGenerationException: Unknown integral data type for ids : java.lang.String
---- many lines below
at ajfmo.studycontrol.DAO.StudentDAO.createStudent(StudentDAO.java:49)

经过多次尝试并接着大量的“教程”,视频和指南后,我仍然无法使其正常工作......

如果你有一个类似案例的例子,我会非常感激,如果你向我显示

这些是我的POJO / BEANclasses。

Student.java

// imports

@Entity
@Table(name = "student", catalog = "students")
public class Student implements java.io.Serializable {

private static final long serialVersionUID = -5712510402302219163L;
private String studentId;
private Career career;
private Section section;
private String studentName;

public Student() {
}

public Student(String studentId, String studentName, Career career, Section section) {
    this.studentId = studentId;
    this.studentName = studentName;
    this.career = career;
    this.section = section;
}

@Id
@GeneratedValue
@Column(name = "student_id", unique = true, nullable = false)
public String getStudentId() {
    return this.studentId;
}

public void setStudentId(String studentId) {
    this.studentId = studentId;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "student_career", nullable = false, foreignKey = @ForeignKey(name = "fk_student_career"))
public Career getCareer() {
    return this.career;
}

public void setCareer(Career career) {
    this.career = career;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "student_section", nullable = false, foreignKey = @ForeignKey(name = "fk_student_section"))
public Section getSection() {
    return this.section;
}

public void setSection(Section section) {
    this.section = section;
}

@Column(name = "student_name", nullable = false, length = 100)
public String getStudentName() {
    return this.studentName;
}

public void setStudentName(String studentName) {
    this.studentName = studentName;
}

/*
 * (non-Javadoc)
 * 
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    return "Student [studentId=" + studentId + ", career=" + career + ", section=" + section + ", studentName="
            + studentName + "]";
}

}

Career.java

// Imports

/**
 * Career generated by hbm2java
 */
@Entity
@Table(name = "career", catalog = "students", uniqueConstraints = @UniqueConstraint(columnNames = "career_name"))
public class Career implements java.io.Serializable {

private static final long serialVersionUID = 4710263584653513266L;
private String careerId;
private String careerName;
private Set<Student> students = new HashSet<Student>(0);

public Career() {
}

public Career(String careerId, String careerName) {
    this.careerId = careerId;
    this.careerName = careerName;
}

public Career(String careerId, String careerName, Set<Student> students) {
    this.careerId = careerId;
    this.careerName = careerName;
    this.students = students;
}

public Career(Career studentCareer) {
    this.careerId = studentCareer.careerId;
}

@Id
@GeneratedValue
@Column(name = "career_id", unique = true, length = 25)
public String getCareerId() {
    return this.careerId;
}

public void setCareerId(String careerId) {
    this.careerId = careerId;
}

@Column(name = "career_name", unique = true, length = 100)
public String getCareerName() {
    return this.careerName;
}

public void setCareerName(String careerName) {
    this.careerName = careerName;
}

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "career_id")
public Set<Student> getStudents() {
    return this.students;
}

public void setStudents(Set<Student> students) {
    this.students = students;
}

/*
 * (non-Javadoc)
 * 
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    return careerName;
}

}

Section.java

// Imports

/**
 * Section generated by hbm2java
 */
@Entity
@Table(name = "section", catalog = "students", uniqueConstraints = @UniqueConstraint(columnNames = "section_name"))
public class Section implements java.io.Serializable {

private static final long serialVersionUID = 6380772442291491780L;
private String sectionId;
private String sectionName;
private Set<Student> students = new HashSet<Student>(0);

public Section() {
}

public Section(String sectionId, String sectionName) {
    this.sectionId = sectionId;
    this.sectionName = sectionName;
}

public Section(String sectionId, String sectionName, Set<Student> students) {
    this.sectionId = sectionId;
    this.sectionName = sectionName;
    this.students = students;
}

public Section(Section studentSection) {
    this.sectionId = studentSection.sectionId;
}

@Id
@GeneratedValue
@Column(name = "section_id", unique = true, length = 25)
public String getSectionId() {
    return this.sectionId;
}

public void setSectionId(String sectionId) {
    this.sectionId = sectionId;
}

@Column(name = "section_name", unique = true, length = 200)
public String getSectionName() {
    return this.sectionName;
}

public void setSectionName(String sectionName) {
    this.sectionName = sectionName;
}

@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "section_id")
public Set<Student> getStudents() {
    return this.students;
}

public void setStudents(Set<Student> students) {
    this.students = students;
}

/*
 * (non-Javadoc)
 * 
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    return sectionId;
}

}

这些是我的DAO课程:

StudentDAO.java

// Imports

public class StudentDAO {

// Objects
private final Session session = HibernateUtil.getSessionFactory();
private Transaction transaction = null;

private Set<Student> students = new HashSet<Student>();
private Career career;
private Section section;
private Student student;

/**
 * Create student in database
 */
public void createStudent(String studentId, String studentName, Career studentCareer, Section studentSection) {
    career = new Career(studentCareer);
    section = new Section(studentSection);
    student = new Student(studentId, studentName, studentCareer, studentSection);
    students.add(student);
    career.setStudents(students);
    section.setStudents(students);
    try {
        transaction = session.beginTransaction();
        session.save(career);
        session.save(section);
        session.save(student);
        transaction.commit();
    } catch (HibernateException e) {
        e.printStackTrace();
    }
    HibernateUtil.shutdown();
}

public List<Career> careerCriteria() {
    CriteriaBuilder builder = session.getCriteriaBuilder();
    CriteriaQuery<Career> criteria = builder.createQuery(Career.class);
    Root<Career> root = criteria.from(Career.class);
    criteria.select(root);
    List<Career> resultset = session.createQuery(criteria).getResultList();
    return resultset;
}

public List<Section> sectionCriteria() {
    CriteriaBuilder builder = session.getCriteriaBuilder();
    CriteriaQuery<Section> criteria = builder.createQuery(Section.class);
    Root<Section> root = criteria.from(Section.class);
    criteria.select(root);
    List<Section> resultset = session.createQuery(criteria).getResultList();
    return resultset;
}
}

CareerDAO.java

public class CareerDAO {

// Objects
private Career career;

// Hibernate Utils
private Session session = HibernateUtil.getSessionFactory();
private Transaction transaction = null;

/***************/
/***         ***/
/*** Methods ***/
/***         ***/
/***************/

public void createCareer(String careerID, String careerName) {
    career = new Career(careerID, careerName);
    try {
        transaction = session.beginTransaction();
        session.save(career);
        transaction.commit();
    } catch (HibernateException e) {
        e.printStackTrace();
    }
}
}

SectionDAO.java

public class SectionDAO {

// Objects
private Section section;

// Hibernate
private Session session = HibernateUtil.getSessionFactory();
private Transaction transaction = null;

/***************/
/***         ***/
/*** Methods ***/
/***         ***/
/***************/

public void createSection(String sectionID, String sectionD) {
    section = new Section(sectionID, sectionD);
    try {
        transaction = session.beginTransaction();
        session.save(section);
        transaction.commit();
    } catch (HibernateException e) {
        e.printStackTrace();
    }
}
}

这是我的学生视图控制器。

package ajfmo.studycontrol.view;

//Imports

public class StudentView implements Initializable {

// Objetos

// Colections

// FXML objects

/***************/
/***         ***/
/*** Methods ***/
/***         ***/
/***************/

/**
 * Fill Carrer's ComboBox
 * 
 * @param careersList
 */
private void fillCareersCbo(ObservableList<Career> careersList) {
    for (Career careers : student.careerCriteria()) {
        careersList.add(new Career(careers.getCareerId(), careers.getCareerName()));
    }
}

/**
 * Fills Section's ComboBox
 */
private void fillSectionsCbo(ObservableList<Section> sectionList) {
    for (Section sections : student.sectionCriteria()) {
        sectionList.add(new Section(sections.getSectionId(), sections.getSectionName()));
    }
}

/**
 * Events listeners
 */

/**
 * Calls 'createStudent' method from StudentDAO
 */
@FXML
private void create() {
    student.createStudent(txtCodigo.getText(), txtNombre.getText(), cboCarrera.getValue(),
            cboSeccion.getValue());
}

/**
 * Close SessionFactory and current window
 */
@FXML
private void salir() {
    HibernateUtil.shutdown();
    Stage stage = (Stage) btnSalir.getScene().getWindow();
    stage.close();
}
}

非常感谢您阅读所有这些内容。

P.S。:非常感谢任何额外的建议。

1 个答案:

答案 0 :(得分:0)

我认为可能的问题是:

    @Id
    @GeneratedValue
    @Column(name = "student_id", unique = true, nullable = false)
    public String getStudentId() 
    @Id
    @GeneratedValue
    @Column(name = "career_id", unique = true, length = 25)
    public String getCareerId() 
    @Id
    @GeneratedValue
    @Column(name = "section_id", unique = true, length = 25)
    public String getSectionId()

@GeneratedValue注释不能用于String为数据类型的字段

相关问题