java - 如何自动增加postgresql中的id?

标签 java postgresql hibernate

问候.. 我正在尝试将对象添加到我的 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/

相关文章:

java - Java SE 的 ManagedExecutorService、ManagedTask 和 ManagedTaskListener 替代方案

postgresql - 将列转置为行 - postgres

c# - 我可以将 Parallel.For 与 sql 命令一起使用吗?

java - hibernate保存中的可序列化字符串(对象实体,可序列化id)

hibernate - Grails 在域[re​​wards.OnlineOrder] 引用[rewards.OrderItem] 上缺少列[order_items_order_item] 的类型或列

java - 使用注释在 Hibernate 中使用复合主键

对数组进行排序时出现 java.lang.ArrayIndexOutOfBoundsException

java - Spring Data Neo4j 4.x 和 sdn-大学 : Neo4jTemplate no autowire'ing

java - Java模式的优势,其中方法将对象作为参数而不是单个参数

postgresql - Redshift : New table but Group members can't query