jpa,列中唯一会影响另一列

时间:2019-03-20 05:57:25

标签: java spring hibernate spring-boot spring-data-jpa

我正在使用Spring Boot,JPA,H2。

我的实体类是这个。

@Entity
@Table(name="product")
public class Product {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private long id;
  @Column(name="name", unique=true)
  private String name;
  private String attr1;
  private String attr2;
}

,我试图在类路径中使用'data.sql'初始化示例数据。是这个。

insert into product values(1, 'hong', 'attr1', 'attr2');
insert into product values(2, 'kim', 'attr1', 'attr2');

但是我得到了错误

Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #2 of URL [file:/D:/OneDrive%20-%20IOChord/personal/develop/workspace/workspace_spring/jpa-00-basic/target/classes/data-h2.sql]: insert into product values(2, 'kim', 'attr1', 'attr2'); nested exception is org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "UK_JMIVYXK9RMGYSRMSQW15LQR5B_INDEX_1 ON PUBLIC.PRODUCT(NAME) VALUES ('attr2', 1)"; SQL statement:
insert into product values(2, 'kim', 'attr1', 'attr2') [23505-197]

但当我更改此内容

insert into product values(1, 'hong', 'attr1', 'attr2');
insert into product values(2, 'kim', 'attr3', 'attr3');

这有效。我只想只配置一个列(列“名称”)是唯一的。但它会影响另一个列attr1,attr2。为什么会这样?

1 个答案:

答案 0 :(得分:3)

数据库中列的顺序可能与您实体中的顺序不同,这应该做到:

insert into product(id, name, attr1, attr2) values(1, 'hong', 'attr1', 'attr2');
insert into product(id, name, attr1, attr2) values(2, 'kim', 'attr1', 'attr2');