Greeting.. I'm trying to add objects to my PostgreSQL database everything works fine but when i add the second object in the database it only overwrite the first one
Student Class
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition="serial")
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;
}
hibernate.cfg.xml
<!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>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.username">user1</property>
<property name="hibernate.connection.password">test123</property>
<property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/hb_student_tracker</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="connection_pool_size">1</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
CreatStudentDemo.java
public static void main(String[] args) {
//create session Factory
SessionFactory factory = new Configuration()
.configure()
.addAnnotatedClass(Student.class)
.buildSessionFactory();
//create Session
Session session = factory.getCurrentSession();
try {
System.out.println("Creating new Studnet Object..");
//create Student Object
Student student = new Student("Souid","Ayoub","ayoub@luv2code.com");
//start the transaction
session.beginTransaction();
//save the object
System.out.println("Saving the Student...");
session.save(student);
//commit the transaction
session.getTransaction().commit();
System.out.println("Done !");
} finally {
factory.close();
}
}
My table SQL
CREATE TABLE public.student
(
id integer NOT NULL DEFAULT nextval('student_id_seq'::regclass),
email character varying(255) COLLATE pg_catalog."default",
first_name character varying(255) COLLATE pg_catalog."default",
last_name character varying(255) COLLATE pg_catalog."default",
CONSTRAINT student_pkey PRIMARY KEY (id)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE public.student
OWNER to user1;
the first object is written fine in the database the second one will overwrite the first one