MongoDB Morphia - Unique

I am trying to have serial db where the username and email address are unique.

http://www.mongodb.org/display/DOCS/Indexes#Indexes-unique%3Atrue

http://code.google.com/p/morphia/wiki/EntityAnnotation

My user class is as follows:

public class User {
    @Indexed(unique = true)
    @Required
    @MinLength(4)
    public String username;

    @Indexed(unique = true)
    @Required
    @Email
    public String email;

    @Required
    @MinLength(6)
    public String password;

    @Valid
    public Profile profile;

    public User() {
...

I used the @Indexed annotation (unique = true), but it does not work. There are more duplicates in my db.

Any ideas how I can fix this?

Edit:

I read about providing Indexes, but it seems like the wrong approach, I don't want to download duplicate data, just to see that it is really a duplicate.

I want to block it right away.

somthing like

try{

ds.save(user);
}
catch(UniqueException e){
...
}
+5
source share
5 answers

JPA Bean Validation, ? ( Bean validate()) . , , .

. MongoDB - , , , mongodb , t , mongodb, , :(

2

, 2 , , db.things.ensureIndex({email: 1}, {unique: true} );?? . http://www.playframework.org/documentation/2.0/JavaGlobal

+1

A , , , .

ensureIndex mongo:

db.user.ensureIndex({'username':1},{unique:true})
db.user.ensureIndex({'email':1},{unique:true})

.. , :

db.user.getIndexes()

Morphia WriteConcern.SAFE, , , .

+5

, play framework 1.2.6 morphia 1.2.12.

@Indexed (unique = true) , . , " " , , .

, , :

> db.Account.drop()
true

: ( ...)

> db.Account.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "ns" : "something.Account",
                "name" : "_id_"
        },
        {
                "v" : 1,
                "key" : {
                        "email" : 1
                },
                "unique" : true,
                "ns" : "something.Account",
                "name" : "email_1"
        }
]

, , MongoException.DuplicateKey.

0

, Datastore.ensureIndexes() MongoDB. , Morphia. . , , .

Morphia m = ...
Datastore ds = ...

m.map(Product.class);
ds.ensureIndexes(); //creates all defined with @Indexed
0

Morphia @Entity.

, - Author:

  • , , @Indexed Entity, :

    m.map(Author.class);

    ds.ensureIndexes();

  • mongo db

    b.Author.getIndexes()

, , ( Entity - Author, )

This scenario is obvious in many cases when you want to reuse the Entity class if the schema is the same

0
source

All Articles