Grails Cannot get property 'id' on null object - grails

I am getting this error: Cannot get property 'id' on null object and i can't understand the problem.
Here is my code in provionController.groovy
CreateCriteria returns one element, I verified in the database, size = 1 but when i tried to display the Id, I get this error.
def prov_model = null
def model = Provision_model.CreateCriteria{
gilt_air{
eq("air",air)
}
gilt_coo{
eq("coo",coo)
}
le("date_from", per.begin)
ge("date_to", per.end)
eq("active", 1)
}
println(model.size())
prov_model = model[0]
println(prov_model.id)
but when I am getting it directly by method get(), it hasn't no problem
prov_model = Provision_model.get(57)
println(prov_model.id)

1st: the method is called createCriteria(), not CreateCriteria()
2nd: the method itself DOES NOT invoke any db operation. You have to call list() or get() etc. on it to get the query results

If order to execute the query and store the results in model, replace this
def model = Provision_model.CreateCriteria
with
def model = Provision_model.withCriteria

#injecteer and #Donal both have very valid input. First, you need to address the syntax issue, here is an example of one way to format your criteria:
def prov_model = null
def model = Provision_model.createCriteria().get() {
gilt_air{
eq("air",air)
}
gilt_coo{
eq("coo",coo)
}
le("date_from", per.begin)
ge("date_to", per.end)
eq("active", 1)
}
Keep in mind that by using .get() you are limiting the return from the criteria to one record. Second, if you try writing the criteria both ways, using withCriteria and using the format above and it still doesn't work, your problem may be in the domain model or the configuration of the database.

Related

Jena java.util.ConcurrentModificationException with execConstruct

executing the following code:
Query query = QueryFactory.create(queryString);
QueryExecution qexec = QueryExecutionFactory.create(query, model);
Model m = qexec.execConstruct(model);
System.out.println(m.toString());
model.close();
sometimes arises the java.util.ConcurrentModificationException exeception, depending on the type of query I'm executing. There is a way to build an always-safe snippet of code? Thank you.
Use Model m = qexec.execConstruct() (no model argument) then call model.add(m).
If you query and insert statements on the same model, via execConstruct(model)) there is a risk of CCME. Using a different model for the results avoids that.

grails getPersistentValue() value changes without saving

I am using the getPersistentValue() method to determine how a property changed. However I've discovered that this method returns different values even if I have not explicitly saved the object.
Here's what I've narrowed it all the way down to...
trip.properties=[start:params.startmile,
end:params.endmile,
satusFlag:params.statusFlag,
description:params.description
];
// print statusFlag for checking
log.debug(trip.getPersistentValue('statusFlag')+":"+trip.statusFlag);
def driver=driverService.getValidDriver(params.driver,params.date);
//the persistent value of statusFlag has changed!!!!
log.debug(trip.getPersistentValue('statusFlag')+":"+trip.statusFlag);
The service call is just another criteria search to return a driver if he/she was employed at a date
def driver=Drivers.createCriteria().get{
and{
eq('id',id);
eq('division',division);
le('startDate',compareDate);
or{
ge('endDate',compareDate);
isNull('endDate');
}
}
};
return service
For some reason this query in a service forces my other objects to update their persistent values? Can someone explain why and how to avoid this?
I was able to solve this by importing the transaction annotation
import org.springframework.transaction.annotation.Transactional
and then adding
#Transactional(readOnly = true)
before the method that was being called.
However this won't work in all cases because not all service calls will be read only.

EntityFrameworkCore FromSql method call throws System.NotSupportedException

So am using AspNetCore 1.0 with EFCore 1.0, both latest releases as far as I am aware.
Executing a query to delete an object using the FromSql method on a DbSet throws an exception. Both the code and exception are below.
public void DeleteColumn(int p_ColumnID)
{
int temp = p_ColumnID;
string query = "DELETE FROM Columns WHERE ID = {0}";
var columnsList = m_context.Columns.FromSql(query, p_ColumnID).ToList();
foreach (Columns c in columnsList)
{
m_context.Columns.Remove(c);
}
m_context.SaveChanges();
}
After executing the FromSql call, I get the following exception
An exception of type 'System.NotSupportedException' occurred in Remotion.Linq.dll but was not handled in user code
Additional information: Could not parse expression 'value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[ASPNET5_Scrum_Tool.Models.Columns]).FromSql("DELETE FROM Columns WHERE ID = {0}", __p_0)': This overload of the method 'Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql' is currently not supported.
I have no clue how to fix this error and from Googling I have come across no similar problems.
I am also wondering, if the query/code was successful it would return an 'IQueryable object. Would that solely contain the results of the query, in this case the specific Column object to delete?
FromSql is intended to allow you to compose a custom SQL SELECT statement that will return entities. Using it with a DELETE statement is not appropriate here, since your goal is to load the records you want to delete and then delete them using the default Entity Framework mechanism. A Delete statement generally does not return the records deleted (though there are ways to accomplish that). Even if they did, the records will already be deleted and so you won't want to iterate over them and do a Remove on them.
The most straightforward way to do what you want might be to use the RemoveRange method in combination with a Where query.
public void DeleteColumn(int p_ColumnID)
{
m_context.Columns.RemoveRange(m_context.Columns.Where(x => x.ID == p_ColumnID))
m_context.SaveChanges();
}
Alternately, if you want to load your entities and iterate manually through them to
public void DeleteColumn(int p_ColumnID)
{
columnList = m_context.Columns.Where(x => x.ID == p_ColumnID);
foreach (Columns c in columnsList)
{
m_context.Columns.Remove(c);
}
m_context.SaveChanges();
}
If you really want to issue the Delete statement manually, as suggested by Mike Brind, use an ExecuteSqlCommand method similar to:
public void DeleteColumn(int p_ColumnID)
{
string sqlStatement = "DELETE FROM Columns WHERE ID = {0}";
m_context.Database.ExecuteSqlCommand(sqlStatement, p_ColumnID);
}
I had the same exception in a case where I did not use delete statement. Turns out I was using the In-Memory Database. Since it is not a real database you can't use FromSQL.

how to get data from database to controller in grails 3

i am new in grails 3 and i wanted to know that how we can get the values from the database to the controller
i tried
def std = Students.get(1)
but it returns only the id not the actual value
plzzzz can anyone help me
You could also do:
def std = Students.findById(id);
If you are printing the result of get, the toString() default methods is call if you haven't create your own. Then if you do:
def std = Students.get(1)
println std
Students: 1 will be printed
You can implement your toString() method as:
Students{
String name
String toString(){
name
}
}
In this case the result of println will be its name.
If you want to print all fields of the object just do
println std.dump()

Grails: Error while applying criteria Query

I am applying some criteria query to find the sum of columns and save the result in long format. When there is data in the table, it is working fine, but in case no match records are found, the following error is thrown:
Cannot cast object 'null' with class 'null' to class 'long'**
My code is:
long referralPoints = ReferralDetail.createCriteria().get {
eq('referredBy', user)
projections {
sum('referralPoints')
}
}
Use Long instead of long. Primitives cannot be null.

Resources