Question

In the Grails Doc: http://grails.org/doc/2.3.x/guide/GORM.html It says that adding a unique constraint in a 1:1 is good practise.
So if a face has one nose, we should do:

class Face {
    static hasOne = [nose:Nose]
    static constraints = {
        nose unique: true
    }
}

But Why? Surely, the constraint is implicit in the cardinality?

So why should we do it?

Was it helpful?

Solution

The reason for putting the unique constraint is to ensure that two faces don't have the same nose. Since this is a 1:1 relationship the Id of the nose is kept on the face. That's why.

OTHER TIPS

To be sure that only one nose knows the current face.

Without this constraint :

Face face = new Face();
Nose nose1 = new Nose();
face.nose = nose1;
face.save(flush: true);

Nose nose2 = new Nose();
face.nose = nose2;
face.save(flush: true); // no error, but in DB, nose1 and nose2 reference the same face_id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top