【问题标题】:Unique constraint error on inserting data插入数据时的唯一约束错误
【发布时间】:2019-07-02 21:11:10
【问题描述】:

我收到奇怪的错误原因:

java.sql.SQLIntegrityConstraintViolationException: ORA-00001: 唯一约束

在执行我下面的代码时:

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. 

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

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>

【问题讨论】:

  • 仅仅创建一个序列没有任何作用。如果您有 - 通过触发器或作为列的默认值,您是如何将其与表关联的?

标签: java oracle hibernate


【解决方案1】:

您的 id 字段 serial_number 是一个初始化为零的 int,并且您的 @Id 映射不包含 @GeneratedValue 注释,因此 hibernate 将假定您手动分配 id 并在每次您时将其保存为零持久化一个对象,导致SQLIntegrityConstraintViolationException。你需要添加一个@GeneratedValue 注解,你也可以选择一个策略,像这样:

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

【讨论】:

  • 谢谢。有用!我用过@GeneratedValue(strategy = GenerationType.SEQUENCE)
  • @GeneratedValue(strategy = GenerationType.AUTO) 会使用我的表中创建的序列吗?因为我总是看到这一行 Hibernate: select hibernate_sequence.nextval from dual
猜你喜欢
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多