问候.. 我正在尝试将对象添加到我的 PostgreSQL 数据库中,一切正常,但是当我在数据库中添加第二个对象时,它只会覆盖第一个对象
学生类
@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();
}
}
我的表 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;
第一个对象在数据库中写入正常,第二个将覆盖第一个
最佳答案
我认为您的问题是对@Id 列使用原始类型。
这里是 Hibernate 对 javadoc 中的 save()
方法的说明;
Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
CrudRepository#save()
方法检查数据库中的学生 ID,第一条和第二条记录均为 0。由于 Hibernate 找到了一条记录并认为您没有插入一条记录,相反,您正在更新一条 id 为 0 的记录。
如果您像下面那样修改代码,它应该可以工作;
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition="serial")
private Integer id;
现在,Hibernate 将检查您的 id,如果它是一条新记录,则 id 字段将为空,因此 Hibernate 说这是一条新记录,应该将其作为新记录插入。
另外,还有一件事。您在 hibernate 配置中设置了 hbm2ddl.auto
。您可以查看 hbm2ddl.auto
的更多详细信息,in here .
<property name="hbm2ddl.auto">create</property>
在这种情况下,一旦 CreatStudentDemo
工作,hibernate 就会破坏您的旧表。也就是说,它删除了 Student 表并创建了一个新表。然后它按预期在数据库中创建学生记录,比方说 Student1。
事情是这样的,您重新运行 CreatStudentDemo
并且您希望第二个对象将作为 Student2 插入。然而,这才是真正发生的事情——当您重新运行 CreatStudentDemo
时,hibernate 会破坏 Student1 被删除的表。然后它创建 Student 表并插入 ID 为 1 的 Student 对象,因为这是新创建的 Student 表上的第一条记录。
基本上可以设置;
<property name="hbm2ddl.auto">update</property>
或者,你可以调用两次save()
方法,比如;
Student student = new Student("Souid","Ayoub","ayoub@luv2code.com");
Student student2 = new Student("Test Student","TestStudent","test@mail.com");
//start the transaction
session.beginTransaction();
//save the object
System.out.println("Saving the Student...");
session.save(student);
session.save(student2);
.....
关于java - 如何自动增加postgresql中的id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58033027/