Update "lastUpdated" Field in Parent Domain Class in Grails - grails

I have a parent domain class the has a hasMany of another domain class. Both the parent and the child domain classes have the lastUpdated and the dateCreated fields. My issue is that when I update a child domain class, I need the parent domain class to reflect that change and update its lastUpdated field as well.
Is there any mapping or other configuration between the parent and child that Grails provides that would implement this feature?
Update
I added the following lines to the child domain class:
def beforeUpdate = {
parent.lastUpdated = new Date()
}
I also had to make sure in the controller that when I updated a child, I also had to save the parent as well to persist the new lastUpdated field. This seems to work fine, but I would still like to know if there is a mapping or something similar that would do this.

I have a feeling your suggested implementation will be buggy. You're updating the parent by setting the lastUpdated date manually, which might cause grails to update lastUpdated again after it does dirty checking on it. If that's the case, you would actually end up with a lastUpdated time that occurred after the date you original set. In your testing, this might be only a few (milli)seconds, but you can't guarantee that.
Not only that, but your implementation is harder to maintain since you have increased the coupling of Parent and Child.
Might I suggest another implementation? The lastUpdated field is supposed to represent the time the specific domain object was updated. The date you're looking for is not quite the same thing, so I wouldn't try to use the existing convention in the "wrong" way. It sounds like the date you want for the parent object is "the last time a child was modified".
Use a formula instead.
To do that, you could use a formula. With a formula, you get exactly what you want without having to directly modify the parent object, and you can still use dynamic finders and other Grails sugar.
class Parent {
...
Date lastChildUpdated
static hasMany = [ children: Child ]
static mapping = {
...
lastChildUpdated formula: '(SELECT max(c.last_updated) FROM child c WHERE c.parent_id = id)'
}
}
GORM will load the value of the formula in whenever you read the object from the database. Now, whenever you save a Child, the parent will have an accurate value for that property without having to touch the Parent.

I used a hack. I have added a Long updateTrigger field to my parent domain class and a touch method:
class Parent {
Long updateTrigger
static mapping = {
autoTimestamp true
}
static constraints = {
updateTrigger(nullable:true)
}
public touch() {
if (updateTrigger == null) updateTrigger = 0
updateTrigger++
this
}
In the update/save actions of the child controller, I just call:
child_instance.save() // save the child
child_instance.parent.touch().save() // updates parent's time stamp
This will increment the updateTrigger value, and the save() will automatically update the lastUpdated field thanks to the autoTimestamp set to true in the mapping. updatedTrigger is set to be nullable so that it doesn't invalidate any existing database table and therefore can be added anytime to any domain class.

In one of my project where the domain was like.
A Program has many AdvertisingMaterial and we have subclasses of AdvertisingMaterial, FlashAd, ImageAd etc. The user want the ability to filter the programs which has flashAds, imageAds etc. Now I need to do the filtering on the basis of the class property that we have in database table (When table tablePerHierarchy is true). So I did some changes in my domain class to get this property.
class AdvertisingMaterial {
String className
static constraints = {
className(nullable: true)
}
static mapping = {
className formula: 'CLASS'
}
}
Now what I can use this className field in my dynamic finders and criteria query as well. So I can do something like
List<AdvertisingMaterial>adMaterials=AdvertisingMaterial.findAllByClassName("com.project.FlashAd")
static mapping = {
fullName formula: "CONCAT(FIRST_NAME,' ',LAST_NAME)"
totalAmount formula: "SUM(AMOUNT)"
}

Related

Find subdomain using domain instances in Grails

In grails, how do I find subdomain using domain instances
Let say I have
class Family {
Integer id
Parent parent
}
class Parent {
Interger id
static hasMany = [children: Child]
}
class Child {
String name
}
So in controller,
Parent mom = Family.findById(1).parent
so now, how do I use mom to get a child with name == "Child" in parent?
Is it even possible?
I think this should work.
Child child = mom.children.find { it.name == 'child' }
But I do not recommend using this kind of queries. Grails has many ways for querying you can read about it here http://gorm.grails.org/latest/hibernate/manual/index.html#querying. I also recommend to you this guide http://guides.grails.org/querying-gorm-dynamic-finders/guide/index.html its about dynamic finders in contrast to queries that use groovy collection methods for querying.
I hope its help full
You can use the criteria API for that:
Parent.withCriteria {
children {
eq("name", "Bob")
}
}
In this example children will be joined to the parent. And all parents will be returned, that have a child called "Bob".
You can simply use closure findAll{} this way:
def childrenList=mom.findAll{it.children.each{
if(it.name=='child')
return it
}
}
This will give you a list of all the children objects with name 'Child'.
As #user615274 has suggested, the accepted solution works but that it may have performance issues.
One feature that Grails shine is the dynamic query. I would modify the Child domain and use dynamic query. eg.
Since Parent "hasMany" relation to Child, the child "belongsTo" the Parent
class Child {
String name
Parent parent
// or static belongsTo = [parent:Parent]
}
Once this relationship is setup, then you can use dynamic query
def child = Child.findByParent(mom) // return the first matching result
def children = Child.findAllByParent(mom) // returns a list of matching result
I hope this helps.

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.

Grails binding one to one associations

When you generate grails views, grails looks at your relationships and generates the right html for your form data to be automatically binded to the back end domain. For one to one associations grails creates a drop down list.
However, you might not want to present that property as a drop down list but something more custom (for example a text field with autocomplete). As soon as you do that the value that comes to the controller from that field, comes in as a String and you have to first:
Clear errors
Perform a findBy based on a given param and assign it to the property of the domain
I really want to avoid doing findBys in the controller as much as possible because it seems like I am doing logic/things that should not go there. The controller should delegate to the Service layer. It is not clear to me from the grails documentation how would I do that by using bindData which seems to work really well with String, date, Integer properties etc.. but I do not see how bindData is used for properties that are other domains.
I also really want to avoid passing the params object to the Service layer as it seems less reusable (or maybe not, correct me if I am wrong). I guess that I do not like how it looks semantically. I would prefer the first over the second:
#Transactional
class WithdrawService {
def addWithdraw(Withdraw withdraw) {
//perform business logic here
}
def createWithdraw(Map params){
//perform business logic here
}
}
Let's take the following example:
class Withdraw {
Person person
Date withdrawDate
}
and the parent lookup table
class Person {
String name
String lastName
static constraints = {
}
#Override
public String toString() {
return "$name $lastName"
}
}
In order for the bind to happen automatically without any extra work grails passes in the following request params to automatically bind the one to one:
person.id
a person map with the id.
[person.id:2, person:[id:2], withdrawDate:date.struct, withdrawDate_month:11, create:Create, withdrawDate_year:2015, withdrawDate_day:10, action:save, format:null, controller:withdraw]
What is the best way to go about this?
Pass two hidden fields that look exactly like this: person.id:2, person:[id:2] that get populated as a result of the Ajax call that populates the autocomplete?
In the controller do a Person.findBySomeKnownProperty(params.someKnownValue)
Or any other approach?

domains have some common fields,extends domain or embedded?

when i design database.I use embedded to embed common fields.but it's can't init dateCreated and createdBy,what'd i do?extends domain or embedded is right way to handle common fields?
code to say?
class Created {
Date dateCreated
Long createdBy
def beforeInsert()
{
dateCreated= new Date()
createdBy=0
}
}
class Updated {
Date lastUpdated
Long updatedBy
//it works?
def beforeUpdate(){
lastUpdated=new Date()
updatedBy=0
}
//it works?
def beforeInsert(){
lastUpdated=new Date()
updatedBy=0
}
}
class CreatedUpdated {
Created created
Updated updated
//Must use the embedded option, or the type of exception, can not find CreatedUpdated
static embedded = ['created','updated']
}
class Term {
String name
CreatedUpdated createdUpdated
static embedded = ['createdUpdated']
Term parent
static hasMany =[terms:Term]
static mapping = {
version false
}
String toString()
{
name
}
static constraints = {
name unique:true,size: 1..20
parent nullable: true
createdUpdated display:false,nullable:true
terms display:false
url url: true
}
}
or use extends?
class Term extends CreatedUpdated{
String name
Term parent
static hasMany =[terms:Term]
static mapping = {
version false
}
String toString()
{
name
}
static constraints = {
name unique:true,size: 1..20
parent nullable: true
terms display:false
url url: true
}
}
`
what is right to me?
I'd definitely make this example embedded rather than inherited. I don't think you should make this call based solely on the fact that objects contain common fields. Instead, you should use inheritance if it makes sense for your model using standard OO design techniques. For example, if "myClass is a myBaseClass" doesn't hold true, inheritance is probably the wrong solution.
In general, I'd stay away from classes like CreatedUpdated that are just a collection of properties and not an actual object from your domain. Java/Groovy has only single inheritance, so this only works if you have one base class like this.
Also, for that particular case, created and updated timestamps can automatically be applied by GORM. If you're using spring security, check out the audit-trail plugin for automatically creating createdBy and updatedBy columns.
In this particular case audit-trail plugin should suffice the requirements. However if you have such requirement for other fields wherein no plugin is available, then one of the possible solution could be to inject such common fields at compile time via AST Transformation. Internally audit-trail plugin uses this concept to inject those fields. Depending upon your requirement you can either use Global AST Transformations or Local AST Transformations.

Grails finding parent by the many side

My problem should be obvious, but I just don't see the light right now :-(
I have two domainclasses like this:
class Parent {
String name
static hasMany = [children: Child]
}
class Child {
String name
}
Now I should be able to find the Parent of a child by using the dynamic finder of the Parent like:
Parent.findByChildren([someChild] as Set)
But I get a hibernate error stating that I've got a grammar error in my hibernate SQL:
Caused by: java.sql.SQLException: No value specified for parameter 1
And for the reference: someChild IS a concrete instance. And I would like to avoid Child to have an explicit parent in the definition.
How then can I go from the Child to the Parent?
Best Regards,
Christian Sonne Jensen
Just to end this question, I wanted to report a solution to my "problem". I'm using a namedQuery in the Parent entity (Customer or Producer) like this:
Class Customer {
static hasMany = [channels: Channel]
static namedQueries = {
findByChannel {
channelId ->
channels {
eq 'id', channelId
}
}
}
}
Then I find the Customer like this:
def customers = Customer.findByChannel(channel.id).list()
In this way the Channel are relieved of the burden of knowing anything about who references it, and I don't have to do any artificial relationship tables.
I still think that it must be some kind of mistake that I cannot use one of the dynamic finders:
Customer.findByChannels([channel] as Set)
Maybe the dynamic finders doesn't take one-to-many relationsships into account, and only works for simple attributes??? (I'm using Grails 1.3.1)
Thanks for your replies though!
Christian Sonne Jensen
If you don't want the parent foreign key on the child, you'll have to create a join table for the parent that serves as a surrogate for the child:
class ParentalRelationship {
static belongsTo = [parent: Parent, child: Child]
}
You could then have helper methods on the parent to query for children through the ParentalRelationship object.
With your real implementation of Customers, Channels, and Producers, chances are that you'd want a many-to-many relationship anyways as a channel wouldn't belong to a single customer (or a single producer).
Maybe a better way is to write in the chield the belongsTo something like this:
static belongsTo = [parent: Parent]
And then you can use:
Chield c = ...
Parent parent = c.parent
I would invert it:
class Parent {
String name
static Set<Child> getChildren() {
Child.findAllByParent(this) as Set
}
}
class Child {
String name
Parent parent
}
This uses the same database structure (the child table has a foreign key to parent) but makes it easy to go from one side to the other without being explicitly bidirectional.
One thing does change. Instead of this:
def parent = ...
parent.addToChildren(new Child(...))
parent.save()
you do this:
def parent = ...
def child = new Child(parent: parent, ...).save()
This is more performant because you don't need to load the entire collection just to persist a new child.

Resources