Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create association by joining non primary key column

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?

like image 350
Lokeshwer Avatar asked Jul 31 '11 06:07

Lokeshwer


People also ask

Can we create entity in Hibernate without primary key?

No, Hibernate will not work without primary key. Every table should have some unique key.

What is referencedColumnName in @JoinColumn Hibernate?

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.

What is @primarykeyjoincolumn?

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 ...

What is @MapsId?

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.


1 Answers

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
   }
}
like image 101
Burt Beckwith Avatar answered Sep 21 '22 22:09

Burt Beckwith