1

my table has 3 columns: ID, City, District.

My web service give in input a list of couples (City, District). I need to avoid couples (City, District) duplicates.

How can I achieve this result? I can't use session.saveOrUpdate() because due to a different ID, all the records seems always different.

Please help me.

Thank you.

2
  • The first thing to do would be to add a constraint to your table: CONSTRAINT city_district_unique UNIQUE (city, district). The exact syntax will vary depending on the database you're using. Commented Mar 7, 2012 at 22:33
  • Maybe you could use a composite key consisting of city and district properties. Commented Mar 8, 2012 at 10:08

1 Answer 1

4

The comment suggests what you should do

CONSTRAINT city_district_unique UNIQUE (city, district)

create a UNIQUE constraint for the fields. This can also be done with JPA annotations when you want to create the table with Hibernate

@Table(name = "yourtable", uuniqueConstraints = {@UniqueConstraint(columnNames = "subject"), ... })

When inserting, you should catch the Exception from the violation of the above constraint and handle it properly, like re-running the insert with changed parameters or ignore it at all. Even better, check your data befor it gets to Hibernate to avoid the invalid inserts beforehand.

Sign up to request clarification or add additional context in comments.

1 Comment

1) is it possible to do it AFTER table creation? 2) I don't find MYSql documentation for your syntax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.