hibernate.cfg.xml file :
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=true</property>
<property name="connection.username">hbstudent</property>
<property name="connection.password">hbstudent</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Entity Class ( Student.java )
package hibernate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="student")
public class Student {
@Id
@Column(name="id")
private int id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="email")
private String email;
public Student() {
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Student [id=" id ", firstName=" firstName ", lastName=" lastName ", email=" email "]";
}
}
package hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import hibernate.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create a student object
System.out.println("Creating new student object...");
Student tempStudent = new Student("Paul", "Doe", "[email protected]");
// start a transaction
session.beginTransaction();
// save the student object
System.out.println("Saving the student...");
session.save(tempStudent);
// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
}
finally {
factory.close();
}
}
}
package hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import hibernate.entity.Student;
public class PrimaryKeyDemo {
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
// create 3 student objects
System.out.println("Creating 3 student objects...");
Student tempStudent1 = new Student("John", "Doe", "[email protected]");
Student tempStudent2 = new Student("Mary", "Public", "[email protected]");
Student tempStudent3 = new Student("Bonita", "Applebum", "[email protected]");
// start a transaction
session.beginTransaction();
// save the student object
System.out.println("Saving the students...");
session.save(tempStudent1);
session.save(tempStudent2);
session.save(tempStudent3);
// commit transaction
session.getTransaction().commit();
System.out.println("Done!");
}
}
This is the Console :
Jul 06, 2022 7:55:06 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {6.0.0.Alpha2}
Jul 06, 2022 7:55:06 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jul 06, 2022 7:55:06 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
Jul 06, 2022 7:55:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Jul 06, 2022 7:55:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=true]
Jul 06, 2022 7:55:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=hbstudent}
Jul 06, 2022 7:55:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jul 06, 2022 7:55:06 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Jul 06, 2022 7:55:07 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jul 06, 2022 7:55:07 PM org.hibernate.envers.boot.internal.EnversServiceImpl configure
INFO: Envers integration enabled? : true
Jul 06, 2022 7:55:07 PM org.hibernate.envers.boot.internal.AdditionalJaxbMappingProducerImpl produceAdditionalMappings
INFO: Generating Envers XML mappings.
Creating 3 student objects...
Saving the students...
Hibernate: insert into student (id, email, first_name, last_name) values (?, ?, ?, ?)
Exception in thread "main" java.lang.ClassCastException: class org.hibernate.id.IdentifierGeneratorHelper$2 cannot be cast to class java.lang.Integer (org.hibernate.id.IdentifierGeneratorHelper$2 is in unnamed module of loader 'app'; java.lang.Integer is in module java.base of loader 'bootstrap')
at org.hibernate.type.descriptor.java.internal.IntegerJavaDescriptor.unwrap(IntegerJavaDescriptor.java:26)
at org.hibernate.type.descriptor.sql.spi.IntegerSqlDescriptor$1.doBind(IntegerSqlDescriptor.java:67)
at org.hibernate.sql.AbstractJdbcValueBinder.bind(AbstractJdbcValueBinder.java:69)
at org.hibernate.sql.ast.tree.expression.LiteralParameter.bindParameterValue(LiteralParameter.java:86)
at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:61)
at org.hibernate.sql.exec.internal.JdbcMutationExecutorImpl.execute(JdbcMutationExecutorImpl.java:109)
at org.hibernate.metamodel.model.domain.internal.entity.SingleTableEntityTypeDescriptor.executeOperation(SingleTableEntityTypeDescriptor.java:768)
at org.hibernate.metamodel.model.domain.internal.entity.SingleTableEntityTypeDescriptor.executeInsert(SingleTableEntityTypeDescriptor.java:384)
at org.hibernate.metamodel.model.domain.internal.entity.SingleTableEntityTypeDescriptor.executeInsert(SingleTableEntityTypeDescriptor.java:376)
at org.hibernate.metamodel.model.domain.internal.entity.SingleTableEntityTypeDescriptor.insertInternal(SingleTableEntityTypeDescriptor.java:204)
at org.hibernate.metamodel.model.domain.spi.AbstractEntityTypeDescriptor.insert(AbstractEntityTypeDescriptor.java:885)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:79)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:643)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:278)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:259)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:313)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:392)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:301)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:208)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:139)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:190)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:36)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:175)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:30)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:71)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:685)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:677)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:672)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:577)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:350)
at jdk.proxy2/jdk.proxy2.$Proxy32.save(Unknown Source)
at hibernate.demo.PrimaryKeyDemo.main(PrimaryKeyDemo.java:32)
I am trying to make objects of student entity and use createstudentdemo to persist data in it. I did persist them and it was visible in database. But then I added
@GeneratedValue(strategy=GenerationType.IDENTITY)
to the @Id in student entity and the code broke I was no longer able to persist data in database using CreateStudentDemo class or PrimaryKeyDemo class. Please help me solve the issue !!
CodePudding user response:
I just learned how to use maven and installed the latest dependencies using maven and everything workd fine.