grails validation when fetching rows - grails

Is it possible to fetch a default value in grails if a column is null? If I were to represent following query via grails domain object then how could I achieve it:
SELECT IFNULL(empsalary,0.00) from Employee;
Domain object:
class Employee{
Integer id,
Float empsalary
static constraints = {
id unique: true, blank:false
empsalary nullable:true
}
}
making empsalary nullable false isn't an option due to existing data
validator on empsalary seems to work when inserting rows but not while data fetch
we can consider writing say getEmpSalary() method on domain and perform check there but there are several other fields we need to do this so trying to avoid massive code changes

If you want a default value to come out of the database without having to code anything into your classes, I suggest you update every row where it is null and set it to 0 in the database. If data is getting inserted from another application and that application is allowing a null value, put a 'DEFAULT 0' on your database column.
Grails also offers an "afterLoad" event which is run when a domain object gets loaded from the database. See the documentation here: http://grails.org/doc/2.3.7/guide/GORM.html.

I think you can do this with HQL:
def salary = Employee.executeQuery('SELECT COALESCE(empsalary, 0.0) FROM Employee')[0]
See this SO Question.

Please try setting Float empsalary = 0.0 in your domain object.

Related

Make field unique based on a boolean field value with multiple column in grails domain

I am using grails-2.5.2 version. I have a field which I want to make unique based on two field. But if the isActive field value is true then it will have one row with the same roll. But if false then multiple entry can be saved with the same roll. My class is below:
class Student {
Integer roll
String name
Boolean isActive
static constraints = {
name(unique: ['roll', 'isActive'])
}
}
Actually I want the unique like this - name(unique: ['roll', 'isActive' == true])
Actually I want the unique like this - name(unique: ['roll',
'isActive' == true])
We don't have any specific support in GORM to express something like that. You will need to express that restriction in your own code in the app.
I am not 100% sure and it may depend on what databases you have to support but I don't think there is going to be a good way to express that kind of restriction in your database either.

How can I update my existing database table using domain class in grails 3.3.0?

I would like to add new column in my existed table using domain class but it is not happening. if I use create-drop in application.yml file then it works but at the same time I lost my data. I needed to keep the data as well as I needed to add new column by updating domain class property in grails 3.3.0 and SQL Server 2012
package com.alumni
class Student
{
String studentId
String studentName
String age
static constraints = {
}
}
Database is not updating with column address
It's unclear from your code snippet, but it sounds like you're trying to add
String address
Note that columns are made NOT NULL by default, so if data exists in the table, it's attempting to add a non-nullable column, with null data on every row, so the column will fail to create. You need to allow this column to be nullable in the constraints block as well
static constraints = {
address(nullable: true)
}
If you add that, the column should create successfully.

Mapping a generated database column to a Grails domain class property

In my Grails 2.5.X app, I have a domain class that looks like this:
class FormData {
String submittedFields
Boolean submitted
static constraints = {
submittedFields nullable: true
}
static mapping = {
// can I do something here to map submitted to a generated
// column of the form_data table
}
}
I would like to map the submitted property to a generated column of the form_data table, i.e. a column that would be created by the SQL statement
alter table form_data add submitted tinyint
GENERATED ALWAYS AS (if(submitted_fields is null,0,1));
Specifically, this generated column should be created when I create the schema from the domain model, e.g. by running the schema-export script.
A consequence of submitted being mapped to a generated column is that the corresponding domain class property should be read-only, or at least, assigning a value to it should have no effect.
If you want to handle the value of the column on database side only, and dont want it to be inserted or updated from grails/hibernate side. you can make the column as insertable:false updatetable:false
static mapping = {
submitted insertable:false, updateable:false
}
Now, even if the value is changed in grails, the new value will not be updated in database.

Grails - Two properties of same type and one does not persist to the database, no errors

Grails 2.0.1
Here are stripped down simplified versions of the Domains:
class Attribute {
String name
static hasMany = [attributeParameters: AttributeParameter]
}
class AttributeParameter {
String name
Attribute attributeReference
static belongsTo = [attribute:Attribute]
}
When I look at the schema in the database, there are 2 separate FKs in AttributeParameter; 1 for the attribute_reference_id, and one for attribute_id. When I save the domains populated with all their data I am getting 0 errors on both Attribute and AttributeParameter, however, the attribute_reference_id column never gets populated. Debugging, I can see the attributeReference object and it has an ID, even after the save call(s). Grails is not throwing any exceptions (at least none that are being displayed on the console).
Stranger still is that if I go to the database and add the ID of an attribute into the attribute_reference_id column, GORM loads it perfectly. Hitting save again, it goes back to null even though debugging shows the object present.
Really at a loss as to why the data isn't persisting.
I had to add the following to Attribute:
static mappedBy = [attributeParameters: 'attribute']

Dynamic MongoDb queries in Grails

I have a domain similar to this in Grails
class User {
static mapWith = "mongo"
ObjectId id
String name
String address
Integer age
}
I am building a search front-end in Grails to query a MongoDb database using the MongoDb plugin. Searching can be done on any of the fields in the database and any field that is not set by the user must be not be used in the query. I.e. no fields shall be compared to null. For example leaving all the fields empty returns all Users but searching for name returns only documents which matches on name.
Initially my queries was simple and I used User.find(new User(params)); in my controller which worked fine. Now I need to be able to also query integer fields using intervals, greater than and less than. I've looked at withCriteria() and to build the query depending on what fields the user have set but so far I've been unsuccessful.
TL;DR
How can I do a query where I don't know which fields the user want to include in the query?
I solved it by using withCriteria() like this:
def c = User.createCriteria()
def users = c.list {
if(params.name)
eq('name', params.name)
if(params.address)
eq('address', params.address)
if(params.age_gt?.isInteger())
gt('age', params.age_gt as Integer)
if(params.age_lt?.isInteger())
lt('age', params.age_lt as Integer)
}

Resources