views:

276

answers:

3

I am trying to use Hibernate to auto increment the id, however, I try to avoid duplication.

class Service
{
    Long id; // auto increment
    String name;
    String owner;
    Boolean incremental;


// setter and getter
}

What I want to achieve is, whenever the new service object I want to save has the same name and owner(no matter if the data field incremental are the same or not) as any of the existing one in the database, it will be a duplicated entry. In this case, I don't want to add another entry into the Database anymore. How to revise the hbm.xml files to avoid this issue?

+1  A: 

You have a number of options:

  • define your primary key as a composite-id or natural-id
  • before saving, use a query to find if there is another row with the same name and owner, and if there is - get it.

Either way you should override hashCode() and equals(..) using name and owner

Bozho
eh.. downvote is why?
Bozho
@Bozho, i think your answer is good... anyone knows why it's down rated?
Lily
@Bozho its back to 0 now +1 I think its good answer as well
c0mrade
+1  A: 

If you need the id column, you can keep it. What you need is * a unique constraint at the database level on both columns.

(if you use hbmtoddl tool, you may need something like that :

<properties name="key" unique="true">
    <property name="name" .../>
    <property name="owner" .../>
</properties>

)

This way, you can not insert duplicates data.

After that if you don't want your code to break when you try to insert duplicates, you need to

  • lookup by name and owner (if you do that often, an index might be a good idea)
  • if you don't find the entry, insert it
  • you might also want to catch the exception thrown in case of unique constraint violation (yes that may still happen if two threads are inserting data at the same time) and retry a select.
Thierry
+2  A: 

You can use annotations to do the same.

On top of your entity class you write the following:

@Table(uniqueConstraints = @UniqueConstraint(columnNames = { "name","owner"}))
@Entity
class Service
{
    Long id; // auto increment
    String name;
    String owner;

// setter and getter
}

This will tell hibernate that the columns name and owner should be unique together.

Shervin
@Shervin Good to know, Shervin (+1)
Arthur Ronald F D Garcia