Cancel/Block the save of a domain object based on some criteria? - grails

i have a need to block or cancel a save of a domain object based on some property.
Can this be done in a constraint?
Example:
An 'Order' domain object has a state of 'invoiced' then the order should not be able to be updated anymore..
Any suggestions on how to tackle this?

I see no reason why you couldn't simply use a constraint for this (as you suggested). Something like this should do it
class Order {
String state
static constraints = {
state(validator: {stateValue, self ->
// only check state if this object has already been saved
if (self.id && stateValue == 'invoiced') {
return false
}
})
}
}
If for some reason you can't use a constraint, here are a couple of alternative suggestions:
Meta-Programming
Use Groovy's method-interception capabilities to intercept calls to save(). Your interceptor should only forward the call to the intercepted save() if the order does not have an invoiced state.
There are some good examples of how to do this in the Programming Groovy book
GORM Events
GORM provides a number of events that are triggered during a persisted objects lifecycle. It may be possible in the beforeUpdate or beforeValidate events to prevent updating the object (I guess throwing an exception would work)

Related

why does save() not save the data and save(flush: true) is required?

RaceRegistration domain has embedded raceParticipant and raceParticipant has a field bibNumber which is Integer.
I have a method for nulling out all bibNumbers of registrations but without flush:true in save, the nulling out of bibs dont work. The bibs are not set to null.
def nullifyBibNumbers(Long id){
...
def regss = RaceRegistration.createCriteria().list(){
eq('compositeEvent', event)
}
regss.each{ r ->
r.raceParticipant.bibNumber = null
r.save()
}
render "Bibs resetted!"
}
If i add flush:true then the bibs are set to null.
regss.each{ r ->
r.raceParticipant.bibNumber = null
r.save(flush: true)
}
I am wondering why you need flush in order for the value to be set to null? I am guessing the problem is with regard to how i am obtain the registration list using createCriteria(). I appreciate any help in this dilemma i am facing. Thanks!
As you probably figured out, save(flush: true) forces Hibernate to write any pending changes to the database. Without the explicit flush, you're relying on a Hibernate transaction to automatically flush when the transaction commits.
The reason only an explicit flush is working for you is because you're not calling save() within a transaction.
The cleanest fix is to create a Grails service, put nullifyBibNumbers() in it, and make the service transactional. That will cause nullifyBibNumbers() to get wrapped in a transaction so that you can use save() without an explicit flush.
If nullifyBibNumbers() is already in a service, you can add #Transactional to the service class, just keep in mind that it will make all methods (perhaps only the public ones?) transactional. Having said that, you can use #NotTransactional on a method to disable transactions.
The value is null in your domain object. But you are talking about null in the database, I guess?
It shouldn't matter. This is basic ORM. As a developer you don't care about when the flush is done. Typically this would be at the end of a transaction. The ORM will then flush all of the changes for that transaction at once.
It works on what is called the first-level cache during the transaction, and tries to avoid going to the db until it is explicitly requested (flush:true) or required (end of transaction).
Without the using of
save(flush: true)
The object will not be persisted immediately.
You can follow the documentation link and see the following information:
The save method informs the persistence context that an instance
should be saved or updated. The object will not be persisted
immediately unless the flush argument is used.
Related to the null issue you are facing make sure that the following condition are met.
The save method returns null if validation failed and the instance was
not persisted, or the instance itself if successful.
You do not need the flush in order for the value to be set to null.
The flush only care of a quick update of the database.
ok i fixed this problem using HQL instead of domain saves. Still i would appreciate why save() didnt work and save(flush:true) saved the data. Thanks!
RaceRegistration.executeUpdate("update RaceRegistration set raceParticipant.bibNumber = null where compositeEvent.id = :ev", [ev: id])

When does grails check for Object Staleness?

I'm using Grails 2.5.1, and I have a controller calling a service method which occasionally results in a StaleObjectStateException. The code in the service method has a try catch around the obj.save() call which just ignores the exception. However, whenever one of these conflicts occurs there's still an error printed in the log, and an error is returned to the client.
My GameController code:
def finish(String gameId) {
def model = [:]
Game game = gameService.findById(gameId)
// some other work
// this line is where the exception points to - NOT a line in GameService:
model.game = GameSummaryView.fromGame(gameService.scoreGame(game))
withFormat {
json {
render(model as JSON)
}
}
}
My GameService code:
Game scoreGame(Game game) {
game.rounds.each { Round round ->
// some other work
try {
scoreRound(round)
if (round.save()) {
updated = true
}
} catch (StaleObjectStateException ignore) {
// ignore and retry
}
}
}
The stack-trace says the exception generates from my GameController.finish method, it doesn't point to any code within my GameService.scoreGame method. This implies to me that Grails checks for staleness when a transaction is started, NOT when an object save/update is attempted?
I've come across this exception many times, and generally I fix it by not traversing the Object graph.
For example, in this case, I'd remove the game.rounds reference and replace it with:
def rounds = Round.findAllByGameId(game.id)
rounds.each {
// ....
}
But that would mean that staleness isn't checked when the transaction is created, and it isn't always practical and in my opinion kind of defeats the purpose of Grails lazy collections. If I wanted to manage all the associations myself I would.
I've read the documentation regarding Pessimistic and Optimistic Locking, but my code follows the examples there.
I'd like to understand more about how/when Grails (GORM) checks for staleness and where to handle it?
You don't show or discuss any transaction configuration, but that's probably what's causing the confusion. Based on what you're seeing, I'm guessing that you have #Transactional annotations in your controller. I say that because if that's the case, a transaction starts there, and (assuming your service is transactional) the service method joins the current transaction.
In the service you call save() but you don't flush the session. That's better for performance, especially if there were another part of the workflow where you make other changes - you wouldn't want to push two or more sets of updates to each object when you can push all the changes at once. Since you don't flush, and since the transaction doesn't commit at the end of the method as it would if the controller hadn't started the transaction, the updates are only pushed when the controller method finishes and the transaction commits.
You'd be better off moving all of your transactional (and business) logic to the service and remove every trace of transactions from your controllers. Avoid "fixing" this by eagerly flushing unless you're willing to take the performance hit.
As for the staleness check - it's fairly simple. When Hibernate generates the SQL to make the changes, it's of the form UPDATE tablename SET col1=?, col2=?, ..., colN=? where id=? and version=?. The id will obviously match, but if the version has incremented, then the version part of the where clause won't match and the JDBC update count will be 0, not 1, and this is interpreted to mean that someone else made a change between your reading and updating the data.

Grails: Is it possible to prevent a domain class instance from being persisted?

I want to create an (one) instance of a Domain class (which, as expected, has a GORM interface to my database) and only use it as a container to pass data around, like a Map object. I want to make absolutely sure that my instance is never going to get persisted in the database. I'm afraid that GORM, with all its cleverness, will somehow manage to save it in the database behind the scene even without an explicit call to save(). Is there a way to specify a "do not persist this" clause when instantiating my object? I know how to prevent persistence on a domain class, what I want is to prevent persistence on a particular instance of the class only.
The solution I have now is to create a class in groovy/src/ that carries the same properties and methods, and use it as my data container, and do type casts as required. It feels wrong, fails DRY, and hacky.
Of course you may also tell me that I should stop being so paranoid and that Grails is never going to persist an domain class instance without an explicit save.
Assume that, you already know how to prevent persistence(table creation) on a domain class. Furthermore, you also know that w/o explicit .save() object won't be persisted.
So, what do you want actually? Is it like.. even if someone accidentally call obj.save(), it will never persist.
Although that doesn't make any sense, but according to your query ,
Is there a way to specify a "do not persist this" clause when
instantiating my object?
Yes, there is a way :
class MyFishyDomain {
String pwd
// properties
// constraints
def beforeInsert() {
if (!this.pwd.equals("drago")) return false
}
def beforeUpdate () {
if (!this.pwd.equals("drago")) return false
}
}
Now..
new MyFishyDomain(pwd:"drago").save() // success
new MyFishyDomain(pwd:"rambo").save() // fail
By the way, if you want to permanently disable Create+Update+Delete But at the same time want to issue query against domain then solution is:
static mapping = {
cache usage: "read-only"
}
def beforeInsert() {
return false
}
Grails will not save an instance of your domain class without an explicit call to save() on the instance. You can create an instance and pass it around, and it will not be persisted.

entity level validator not triggered

I've observed that when I'm adding an entity to a collection of another entity, the validator for the second entity is not called.
I expected that adding to a child collection triggers entity level validation on the parent when savechanges is called.
I can't write a test right now, but if needed I'll would write it this afternoon.
Is this the expected behaviour or a bug?
entity.OrderLine().arrayChanged.subscribe(function (args) {
console.log(args);
if (args.added && args.added.some(function (element) {
console.log(element.entityAspect.entityState.name);
return !(element.entityAspect.entityState.isUnchanged()
|| element.entityAspect.entityState.isDeleted());
})) {
console.log("modifico");
entity.entityAspect.setModified();
}
if (args.removed && args.removed.some(function (element) {
console.log(element.entityAspect.entityState.name);
return !element.entityAspect.entityState.isAdded();
})) {
console.log("modifico");
entity.entityAspect.setModified();
}
});
The parent is not changed automatically by the addition of a child because no data property of the parent changes. That is the technical reason.
Sometimes (often?) the model semantics say that the parent is changed by any addition/deletion/change-to a child. That is not always true which is why Breeze doesn't propagate the change automatically. But it is often true ... and I think it would be a good idea for Breeze to support this for you if you specify this as desired behavior in the metadata. You are not alone in wanting this.
I've added a User Voice suggestion for this idea; please vote for it if it (and add your comments) if it matters to you.
Meanwhile, in an entity initializer you can subscribe to changes in the parent collection and to the items of that collection and have them set the parent to the "Modified" state (parent.entityAspect.setModified()). This will have to do for now I'm afraid.

Emberjs - Temporary disable property changes notification

Is there any simple way to achieve a temporary disabling of notifications of an object property or properties?
I know you can defer them with beginPropertyChanges() and endPropertyChanges() but I don't want those changes to be notified at all until I explicitly enable them.
Thank you in advance.
Use case:
I have to set a property of an object (A) with another object (B). Properties of B are being observed by several methods of other objects. At some time the B object's data gets cleared and the observers get notified, later an HTTP response sets them with something useful. I would not want the observers get notified when clearing the object because the properties values are not valid at that moment.
Ember doesn't support suspending notifications. I would strongly suggest against toying with the private APIs mentioned in the above comments.
I wonder why you bother clearing the object's data prior to the HTTP request? Seems strange.
Using a flag will cause the computed to still trigger.
The best I've come up with is to override the computed with the last known value. Later you can enable it by setting the computed property definition again.
let _myComputedProperty = Ember.computed('foobar', function() {
let foobar = this.get('foobar');
console.log('myComputedProperty triggered >', foobar);
return '_' + foobar + '_';
});
Controller.extend({
turnOffComputed: function() {
let myComputedProperty = this.get('myComputedProperty');
this.set('myComputedProperty', myComputedProperty);
},
turnOnComputed: function() {
this.set('myComputedProperty', _myComputedProperty);
}
})
Full example: Conditional binding for a computed property
This is an old question, but it appears high in Google search for suspending observers, so I would comment.
There are evident use cases for such a feature, for example, an enum property of an object is represented by a list box and the object may change. If the list box is used to request property changes from the server and to set the new value on success, the natural way to do things is to use a controller property with the list box, set that property to the object property when the object changes, and observe it to make requests to the server. In this case whenever the object changes the observer will receive an unwanted notification.
However, I agree that these use cases are so diverse that there is no way Ember can support them.
Thus, a possible work around is to declare a variable in the controller and use it whenever you change a property so that you react only to changes made by the User:
doNotReact: false,
updateManually: function() {
this.doNotReact = true;
Ember.run.scheduleOnce('actions', this, function() {
this.doNotReact = false;
});
............
this.set('something', somevalue);
............
},
onChange: function() {
if (this.doNotReact) return;
...............
}.observes('something')
The value of doNotReact will be reset after the observer gets a chance to run. I do not recommend to reset the stopper variable in the observer since it will not run if you set the property to the same value it already has.

Resources