How to create a Unique constraint?

#1

Hi,

I'm trying to create a unique constraint. Here is a simple example:

@Entity
public class Account {

    @Id
    @GeneratedValue
    private long id;

    @Index(unique="true")
    private String name;
}

The code runs and my Account objects are persisted. But no exception is thrown if name is the same.

What do I need to do to have a Unique constraint?

Thanks,

Carl

 

#2

On a hunch, I tried deleting the database files and restarting the server. Now the Unique constraint works, so the problem is solved.

This leaves one last question... What happens if I want to apply a constraint to an existing database? Can that change be applied to an existing schema?

Thanks,

Carl

 

 

#3

When a new index is added to an entity class that already has instances in the database - the index starts as inactive. To activate it you need to rebuild the index.

Currently the only way to activate the index is to use ObjectDB Doctor to rebuild the entire database.

Future versions of ObjectDB will include a dedicated index rebuilder tool.

By the way, you can use @Unique instead of @Index(unique="true"). Boolean values as strings ("true") is widely used in JDO annotations but it is not very pretty.

Update: Starting ObjectDB 2.6.6 new indexes are automatically built and activated in the background.

ObjectDB Support

Reply