0

I have a table called Topic with two columns: Id(Primary key) and topic(Unique key).

I need to avoid duplicate entries to column 'topic'.

Here is the domain class for the table.

@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 

When I'am inserting duplicate entry,it is trowing sql exception (org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Duplicate entry ).So iam catching that exception and showing a message "item already exists)

 try { topicService.save(tp); } catch (Exception e) { System.out.print("item already exists"); } 

is this the correct method for dealing with unique constraints in Spring data JPA?

1 Answer 1

2

if it is a one column then this should be enough:

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

if unique applies to more than one column combined together , let's say : TOPIC and REF :@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 

if you have multiple combined unique constraints for example :{TOPIC ,REF } AND {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; 
Sign up to request clarification or add additional context in comments.

2 Comments

ok. But when I'am adding the duplicate data its trowing sql exception.Wont hibernate handle this by itself without trowing exception?
no you have to handle that byyourself, at the DAO level for exampl: try { save your entity }catch(DataIntegrityViolationException e){ //handle it here }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.