GORM 1-to-many relationship -- 3 tables created rather than 2 - grails

All
My problem is I'm creating a 1-to-many relationship in GORM and expect 2 database tables to be created as backing objects. 3 are created which makes SQL queries overly complex.
I've created a close variant on the 1-to-many in the GORM documentation:
class Status {
List errorMessage
static hasMany = [errorMessage:ErrorMessage]
}
and the error message class:
class ErrorMessage {
String message
static belongsTo = Status
}
I expected this to create two database tables:
CREATE TABLE status {
ID NUMBER(19,0),
VERSION NUMBER(19,0),
//other fields
}
CREATE TABLE error_message {
ID NUMBER(19,0),
VERSION NUMBER(19,0),
STATUS_ID NUMBER(19,0),
MESSAGE VARCHAR(255)
//other fields
}
but actually it wants a third table,
CREATE TABLE status_text {
status_text_id NUMBER(19,0),
text_idx NUMBER(19,0),
text_id NUMBER(19,0)
}
Adding Status to the ErrorMessage (a hack as I don't want ErrorMessage to have a reference to Status) class removes the third table but keeps the second foreign key resulting in the Text child object having two foreign key fields.
What I want is simple - just a set of objects attached to the parent will be deleted when it is - any thoughts what I'm doing wrong?
Thanks

I don't think you can satisfy both requirements, i.e. that you have cascading deletes and no join table. You need the belongsTo to get cascading deletes and that makes the relationship bidirectional. To remove the join table, name the belongsTo with the Map syntax:
class ErrorMessage {
String message
static belongsTo = [status: Status]
}

Related

how to make first column nullable in one to many relationship join table?

There seems to be a change in behavior from grails 2 to grails3. When i create a one to many relationship like
class Author {
static hasMany = [books: Book]
String name
}
class Book {
String title
}
It will create a join table with columns author_books_id and book_id. In grails 3 it also adds a not null constraint on the first column. In grails 2 not null constraint is not applied. So when i upgrade to grails 3 it is breaking because there are already few records that have first column values to null. It works fine in grails 2 but with grails 3 the first column should not be null. Furthermore the join table is read only so i cannot remove the rows will null first column values. Is there a way to make the first column nullable = true by making changes in domains and not directly in migration file.
The code was extracted from the grails documentation. Please scroll down to one to many section.
6.2.1.2 One-to-many
http://docs.grails.org/3.0.17/guide/GORM.html
Try changing your Book class to this
class Book {
String title
Author author // this creates the belongs to relationship
}
static constraints = {
author nullable:true
}
Also when you recompile the code make sure to delete previous table and start fresh. Grails will not alter any table to delete anythings. It only adds new stuffs.

hasMany mapping table not created

I am having a GORM issue.
I try to map one domain Object with another with hasMany.
class PrototypePriceModifierCode {
...
static hasMany = [activitys:Activity]
...
}
Since I don't need a back reference in Class Activity I don't have any reference to PrototypePriceModifierCode.
Having only this creates my mapping table as expected (1).
prototype_price_Modifier_code_id activity_id
In the Activity, I need a reference to a PrototypePriceModifier, which has nothing to do with the above mapping table.
The problem is that the mapping table is not generated anymore as soon as I define
class Activity{
...
PrototypePriceModifierCode prototypePriceModifierCodeAttached
How can I get the mapping table created and having a reference to PrototypePriceModifierCode in my Activity domain class?
Try like this:
class Activity {
static belongsTo = [PrototypePriceModifierCode]
}
This way, there will be a column in the activity table for PrototypePriceModifierCode instead of creating a separate table for hasMany.
When Activity does not have the prototypePriceModifierCodeAttached property, the hasMany in PrototypePriceModifierCode results in a uni-directional one-to-many association. In the database, this is implemented with a mapping table.
However, when Activity has the prototypePriceModifierCodeAttached property the association changes to a bi-directional one-to-many. In the database this means the activity table has a foreign key pointing to it's prototype_price_modifierCode, so the mapping table is not used. You can read more about these differences here.
"prototypePriceModifierCodeAttached" property
If you want a uni-directional one-to-many and the property Activity.prototypePriceModifierCodeAttached, you can create a getter method which looks up the PrototypePriceModifierCode:
class Activity {
PrototypePriceModifierCode getPrototypePriceModifierCodeAttached() {
PrototypePriceModifierCode.where {
activitys.id == this.id
}.get()
}
}
The downside here is that the property is inaccessible to GORM; can't query on it.
"price_modifier_code_id" column
On the other hand, if what you want is a price_modifier_code_id column in the activity table, you can add it as a long:
class Activity {
long prototypePriceModifierCodeAttached
static mapping = {
prototypePriceModifierCodeAttached column: 'price_modifier_code_id'
}
}
This makes it possible to use GORM queries on the property, but only on the PrototypePriceModifiedCode ID, not the domain class instance itself.
A combo
You can combine both approaches, as long as you're willing to do a bit of maintenance:
class Activity {
long priceModifierCodeId // <--- You gotta maintain this property manually.
PrototypePriceModifierCode getPrototypePriceModifierCodeAttached() {
PrototypePriceModifierCode.get(priceModifierCodeId)
}
}
Note: activitys is misspelled. It should be activities.
I ended up using String saving comma separated ids.
String activitys
this.activitys.split(',')each{
p.activitys.add(Activity.get(Long.parseLong(it)))
}
As I don't need referencial integrity here this works fine for me.

Understanding hasMany behavior in grails and how to save a relationship

I'm making a model where a User fills out many questionnaires and the responses get saved to Questionresponse. I'm on grails 2.5.2
Test1
So I have two models
class User {
String username
...
static hasMany = [reponse: QuestionResponse]
}
class QuestionResponse {
String question_1
String question_2
...
}
With the above, a new DB table is created: user_questionresponse with two columns user_questionresponses_id and questionresponse_id. This seems like what I want. A user would have many questionresponses and those relationships would be saved in this table. However, I can't find out how to save data to this table.
For example, if I do:
def user = springSecurityService.currentUser
def questionnaire = new QuestionResponse(question_1: "foo", question_2: "bar")
//How do I link the user to this newly created questionnaire?
user.addToResponse(q).save(flush: true) //DOES NOT WORK.
Test2 (just add belongsTo)
class User {
String username
...
static hasMany = [reponse: QuestionResponse]
}
class QuestionResponse {
String question_1
String question_2
static belongsTo = [user: User]
...
}
If I add belongsTo to QuestionResponse a new column, user_id, gets created in the DB. Now if I run the same code as above, this user_id column has the id populated with that of the current user. However, the relationship table, user_questionresponse is still empty.
I am aware of the approach mentioned by Burt but I assume that should be required only for ManyToMany relationship. If that is required for all relationship, why isn't that the default?
In your first case, you have a OneToMany relationship between User and QuestionResponse with no side being the owner of the relationship. In this case to maintain the relationship between User and QuestionResponse, a third table is required. To persist data you need to do the:
userInstance.addToResponse(new QuestionResponse(question_1: "foo", question_2: "bar")).save(flush: true, failOnError: true)
You are doing user.addToReponse(q) instead it should be user.addToReponse(questionnaire), if it's not a typo and the data is actually not being stored, then check by adding the failOnError parameter to save() method. Sometimes grails save() method fails silently, it should tell you if this is the case.
In second case, you have added the parent to the relationship, so that means you don't need the third table to maintain the relationship. Grails will not create and populate the third table in this case.
The second approach (adding belongsTo in QuestionResponse) seems the right thing to do in your case, since QuestionResponse objects cannot exists without a user and cannot belong to different users.
In that case there's no need to use a third table.
When you run the app for the first time, grails created the relation table (because there was no belongsTo). When you run the app again with belongsTo grails adds the user_id field but DOES NOT DROP the relation table. That's why the table is there and is empty: it's not needed, but grails database auto-update feature only adds things, it does not remove anything.
The same applies to fields: if you remove a field from an entity you have to manually remove it from the database.

GORM and Composite Keys in associations

I have legacy database and some tables have composite ids
class Client {
String id
static hasMany = [
settings: Setting
]
static mapping = {
id column: 'client_id', generator: 'assigned'
}
}
class Setting {
Client client
String nodeId
String ccyPairPattern
Character qualifier
static mapping = {
id composite: ['client', 'nodeId', 'pattern', 'qualifier']
}
}
I want to delete entry from GORM association:
client.get('1').removeFromSettings(settingToRemove)
// settingToRemove.delete(flush: true)
// delete-orphans does not help
This always raises exception after flush
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) :
This happens because method removeFrom* sets client property to null and generates query to delete with clientId = null as client is part of composite key
What is the best solution in this case. Looks like GORM has poor support for composite keys or my mapping is incorrect.
When you use hasMany without a belongsTo on the many side, in other words a unidirectional association, you get a join table. For example...
class PurchaseOrder {
static hasMany = [items: Item]
}
class Item { }
Would yield three database tables: purchase_order, item, and purchase_order_items. The purchase_order_items table would contain two columns: purchase_order_id and item_id. You can read more about join tables here.
Since you're dealing with a legacy database, I think the best solution is not to use addTo*() and removeFrom*().
Ensure you don't have a join table. If you have a join table, remove the hasMany association.
You'll need to add/remove Setting instances manually.
Example:
def client = Client.get(1)
// Adding a setting
def setting = new Setting(client: client, nodeId: blah...)
setting.save()
// Removing a setting
/*
The prototype is used to search for a domain instance with a composite primary key.
So simply set the composite key properties accordingly.
*/
def prototype = new Setting(client: client, nodeId: blah...)
def setting = Setting.get(prototype)
setting.delete()
Lacking a hasMany association, you won't be able to access a client's settings via the client.settings property. Instead you'd have to query for them like this:
def settings = Setting.findByClient(client)
A consequence of using a legacy database is that if the database doesn't align with that GORM/Hibernate expects it will be limited in what it can do for you.

Access Relationship Table in Grails

I have the following domains classes:
class Posts{
String Name
String Country
static hasMany = [tags:Tags]
static constraints = {
}
}
class Tags{
String Name
static belongsTo = Posts
static hasMany = [posts:Posts]
static constraints = {
}
String toString()
{
"${TypeName}"
}
}
Grails creates an another table in the database i.e. Posts_Tags.
My requirement is:
E.g. 1 post has 3 tags.
So, in the Posts_Tags table there are 3 rows.
How can I access the table Posts_Tags directly in my code so that I can manipulate the data or add some more fields to it.
If you want to access the join table (Posts_Tags) directly, or add properties to it, then you must define it as a separate PostTag domain class. You then split your many-many relationship between Post and Tag into 2 one-to-many relationships (one from Post to PostTag and one from Tag to PostTag).
Here's a comprehensive example of how to perform the mapping and add properties to the join table - in this example Membership is the join table.
Use the normal groovy sql API. For an example of how to get a groovy SQL object and execute sql queries see this

Resources