class Contact {
String name
String number
}
class Message {
String text
String number
Contact contactInfo //If any
}
I need to join on Message.number = Contact.number. Any thoughts on creating association in Grails/GORM with non primary key column?
No, Hibernate will not work without primary key. Every table should have some unique key.
The referencedColumnName attribute tells Hibernate the name of the database column it shall use as the foreign key. There is one small thing left before you can use this association. You need to make sure, that the referenced entity implements Serializable.
It is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is ...
Annotation Type MapsId. @Target(value={METHOD,FIELD}) @Retention(value=RUNTIME) public @interface MapsId. Designates a ManyToOne or OneToOne relationship attribute that provides the mapping for an EmbeddedId primary key, an attribute within an EmbeddedId primary key, or a simple primary key of the parent entity.
I'm pretty sure this isn't possible in GORM, and I don't know if it's even possible in regular Hibernate. But you can fake it:
class Message {
String text
String number
static transients = ['contactInfo']
Contact getContactInfo() {
Contact.findByNumber(number)
}
void setContactInfo(Contact contact) {
number = contact.number
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With