Hibernate:处理独特的约束

时间:2014-07-11 06:27:31

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

我有一个名为Topic的表,有两列:Id(主键)和主题(唯一键)。

我需要避免重复输入列#39;主题'。

这是表的域类。

@Entity
@Table(name="TOPIC",uniqueConstraints = {@UniqueConstraint(columnNames = "TOPIC") })
@DynamicUpdate
ublic class Topic { 
@Id
@GeneratedValue
@Column(name="ID")
private long id;

@Column(name="TOPIC",unique=true)
private String topic;
//getters and setters

当我正在插入重复条目时,它正在进行sql异常(org.hibernate.engine.jdbc.spi.SqlExceptionHelper - 重复条目)。因此我捕获该异常并显示消息" item已经存在)

    try {

        topicService.save(tp);

    } catch (Exception e) {

        System.out.print("item already exists");

    }   

这是处理Spring数据JPA中唯一约束的正确方法吗?

1 个答案:

答案 0 :(得分:2)

如果它是一列,那么这应该足够了:

@Column(name="TOPIC",unique=true)
private String topic;

如果唯一适用于多个列组合在一起,请说:TOPICREF:@ Entity

@Table(name="TOPIC",uniqueConstraints = @UniqueConstraint(columnNames = {"TOPIC","REF"}) )
@DynamicUpdate
public class Topic { 
@Id
@GeneratedValue
@Column(name="ID")
private long id;

@Column(name="TOPIC")
private String topic;
@Column(name="REF")
private String ref;
//getters and setters

如果您有多个组合的唯一约束,例如:{TOPICREF}和{VERSION," TOPIC"}

    @Table(name="TOPIC",uniqueConstraints ={ @UniqueConstraint(columnNames = {"TOPIC","REF"}),@UniqueConstraint(columnNames = {"TOPIC","VERSION"})})
public class Topic { 
    @Id
    @GeneratedValue
    @Column(name="ID")
    private long id;

    @Column(name="TOPIC")
    private String topic;
    @Column(name="REF")
    private String ref;
    //getters and setters
    @Column(name="VERSION")
    private String version;