gpt4 book ai didi

java - 插入数据的唯一约束错误

转载 作者:行者123 更新时间:2023-12-02 03:01:01 27 4
gpt4 key购买 nike

我收到奇怪的错误,原因是:

java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint

执行以下代码时:

Product DAO.java

@Id
@Column(name = "no", columnDefinition = "NUMBER")
private int serial_number;
//No getter and setter for this field

@Column(name = "fname", columnDefinition = "VARCHAR2(50)")
private int fname;

@Column(name = "lname", columnDefinition = "VARCHAR2(50)")
private int lname;
// Getter and setter for fname and lname


ProductService.java

Product po = new Product();
po.setfname = "Tom";
po.setlname = "John";
//I am not setting 'no' field value since I have created sequence in my oracle table to auto increment the value.

当我运行此代码时,我在字段“no”上收到唯一约束错误。任何人都可以帮助我确定我在代码中做错了什么。当我已经在表中为“否”字段创建了序列时,我是否需要在配置文件或代码中进行任何更改?由于它是生产数据库,我也不知道序列名称。

hibernate-cgf.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="hibernate.connection.password">pass</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="dao.Product"></mapping>
</session-factory>
</hibernate-configuration>

最佳答案

您的 id 字段 serial_number 是一个初始化为零的 int,并且 @Id 的映射不包含 @GenerateValue 注释,因此 hibernate 将假定您正在手动分配 id 并保存它每次持久化对象时都将其设置为零,从而导致 SQLIntegrityConstraintViolationException。您需要添加 @GenerateValue 注解,您还可以选择策略,如下所示:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "no", columnDefinition = "NUMBER")
private int serial_number;

关于java - 插入数据的唯一约束错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42349096/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com