postgreshibernate主键生成问题

33qvvth1  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(338)

我正试图使用hibernate orm在employee表中插入一条记录,但不断出现以下错误:

org.hibernate.AssertionFailure: null id in 
com.example.helloworld.entities.Employee entry (don't flush the Session 
after an exception occurs)

如果我传递id值,那么它可以正常工作,但是 @GeneratedValue(strategy = GenerationType.IDENTITY) 它不会产生 'id' 自动地。感谢您的帮助!db模式和实体代码的详细信息如下所示。
数据库引擎:postgres
orm:休眠
我有以下两张表:
表名员工:

Column Name |  Type      |  Length    |  Not Null  | Default
name        | Varchar    |  64        |  true      | NULL 
id          |  int8      |  19        |  true      |nextval(Employee_id::regclass)
company_id  |  int8     |19           |  true      | NULL

表#公司

Column Name |  Type      |  Length    |  Not Null  | Default
Cname       | Varchar    |  64        |  true      | NULL 
id          |  int8      |  19        |  true      | nextval(Company_id::regclass)
area       |  varchar    |64          |  true      | NULL

上述表的实体java类:

@Entity
@Table(name = "Employee")
public class Employee {

    public Employee() {super();}

    @Id
    @Column(name = "id", columnDefinition = "serial")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull
    private long id;

    @NotNull
    @Column(name = "company_id")
    private long company_id;

    @NotNull
    @Column(name = "name")
    private String name;

    @ManyToOne
    private Company company;

   /**
   setters and getters
 **/
}

@Entity
@Table(name = "Company")
public class Company {

    public Company() {super();}

    @Id
    @Column(name = "id", columnDefinition = "serial")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @NotNull
    private long id;

    @NotNull
    @Column(name = "area")
    private String area;

    @NotNull
    @Column(name = "cname")
    private String cname;

    @OneToMany(cascade=CascadeType.ALL)
    @JoinColumn(name="company_id")
    private Set<Employee> employees;

   /**
   setters and getters
 **/
}
41ik7eoe

41ik7eoe1#

我对博士后也有同样的问题。尝试添加 SequenceGenerator 给你的 id 字段:

@Id
@Column(name = "id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="SEQ_EMPLOYEE")
@SequenceGenerator(name="SEQ_EMPLOYEE", sequenceName="SEQ_EMPLOYEE", allocationSize=1)
@NotNull
private long id;

替换 SEQ_EMPLOYEE 数据库中序列的名称。

n9vozmp4

n9vozmp42#

这就是我的工作原理:

@Id
@Column(name = "id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.IDENTITY, generator="seq_name_generated_in_db")
@SequenceGenerator(name="seq_name_generated_in_db", sequenceName="seq_name_generated_in_db", initialValue = 1 , allocationSize=1)

相关问题