1

Edited

(not exact duplicate of How to use @Id with String Type in JPA / Hibernate?)

Reasons:

  • At the time, the error I was getting was this:

    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)
    

    But this wasn't the only error I was getting, I mentioned in the comments that I was having a rough time with this operation because I wasn't able to make it work (beginner).

  • Even the error I was getting by the moment was due to the @GeneratedValue annotation, this annotation wasn't necessary so I could get rid of it and many others.

  • Most important, the exception was not the same

    org.hibernate.TypeMismatchException: Provided id of the wrong type. Expected: class java.lang.String got class java.lang.Long
    
  • I still can't see the relation between the "duplicated post".


Hello and thank you for your time.

As the title says, I need to save data into a table called "student", where student have a career and a section, but career and section have many students.

This is my DB diagram:

Database diagram

I will be posting almost the whole code to make sure you understand what I'm doing. I'm self-learning Hibernate and doing this as a practice, to understand better this tool and improve my skills and knowledge. I do not understand everything that I'm doing but I think I'm going to the good path.

This is my project structure:

Project structure

This is the window where I need to get the job done...

Register a student

I pick an option from the ComboBoxes, and fill the info needed such as ID and Name then click Guardar, or Save in English.

In this moment this is the exception I get:

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)

After several tries and following a ton of "tutorials", videos and guides I can't still make it work properly...

IF YOU HAVE AN EXAMPLE OF A SIMILAR CASE I WILL REALLY APPRECIATE IF YOU SHOW IT TO ME

These are my 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;
}

}

These are my DAO classes:

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();
    }
}
}

And this is my View controller for student.

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();
}
}

Thank you very much for reading all this.

P.S.: any extra suggestions are very appreciated.

AjFmO
  • 395
  • 2
  • 4
  • 18

1 Answers1

0

I think the possible issue is :

    @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 annotation cannot be used on the fields with String as datatype

codeLover
  • 2,571
  • 1
  • 11
  • 27
  • When I remove those annotations then I get this exception. org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session – AjFmO Dec 29 '17 at 06:02
  • It is happening because you are trying to save career, section and student object in a single session. And each object is containing the other 2 objects. Just try saving the student object alone – codeLover Dec 29 '17 at 06:15
  • Ok, done, now I get this WARN SqlExceptionHelper - SQL Error: 1452, SQLState: 23000 ERROR SqlExceptionHelper - Cannot add or update a child row: a foreign key constraint fails (`students`.`student`, CONSTRAINT `fk_student_career` FOREIGN KEY (`student_career`) REFERENCES `career` (`career_name`) ON DELETE NO ACTION ON UPDATE NO ACTION) ERROR ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement] – AjFmO Dec 29 '17 at 06:27
  • Can you tell me what this constraint is: fk_student_career ? And do you have career id which you are putting in you Career object already available in DB? I assume these exceptions are coming while executing createStudent method – codeLover Dec 29 '17 at 06:37
  • Ok, finally solve it, I think the problem was in the database, I settled section and career fields in student table as null and changed nullable to true and was able to make it work, and then reverted changes to NN and nullable = false, removed all extra annotations (GeneratedValue, CascadeType, foreignKey = @ForeignKey), removed also the save career, section and student object in a single session. thanks @Garima Gupta you point me in the right direction but table was corrupted I think. – AjFmO Dec 30 '17 at 14:25
  • Nope! Error, again... Just notice that fk were missing! build them again and getting **This** `WARN SqlExceptionHelper - SQL Error: 1452, SQLState: 23000 ERROR SqlExceptionHelper - Cannot add or update a child row: a foreign key constraint fails (`students`.`student`, CONSTRAINT `fk_student_career` FOREIGN KEY (`student_career`) REFERENCES `career` (`career_name`) ON DELETE CASCADE ON UPDATE CASCADE) ERROR ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]` @Garima – AjFmO Dec 30 '17 at 15:03
  • Please ask a new questions with apt explanation, not in comments........ Kindly mark it as answered if your initial query was resolved – codeLover Jan 01 '18 at 09:30