Not able to get the list of Objects when a hasMany attribute is null.
Class User {
...
List<EMail> emails
static hasMany = [emails: EMail,... ]
static mappedBy = [emails: 'customer',...]
...
}
Where Email is another Class with some String Attributes
Now i am trying to make a simple query as:
Method 1:
def users = User.findAllByEmailsIsEmpty()
This is giving Error as:
Queries of type IsEmpty are not supported by this implementation
Method 2:
def users = User.findAllByEmailsIsNull()
This is giving all the users even those have Email object associated with it.
Then I thought of trying Criteria Query (https://grails.github.io/grails-doc/latest/ref/Domain%20Classes/createCriteria.html )
Method 3:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
sizeEq('emails', 0)
}
This gives No result ( users.size() is 0 )
Method 4:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
isNull('emails')
}
This again gives all the Users even those who don't have emails.
Method 5:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
isEmpty('emails')
}
This gives the Error :
Queries of type IsEmpty are not supported by this implementation
Method 6:
def userCriteria = User.createCriteria()
def users = userCriteria.list(){
eq('emails', null)
}
This again lists down all the users.
PS: Grails is configured with Database as MongoDB.
I would use the grep method. Something like this:
nullEmailUsers = User.list().grep {
!it.emails
}
User.findAll { emails.id != null } do the job!
Related
Getter , setter in test class not getting covered
Here is the code ?
Method :
public static List<SelectOption> UserList
{
get
{
/*string role='';
if(issueTeam == 'Contracts')
role = 'Contract Owner';
else if(issueTeam == 'Buyer')
role = 'Buyer';
else
role = 'Master Data Allocator';*/
UserTemp = [Select u.LastName, u.Id, u.FirstName,u.Name, u.Email From User u ORDER BY u.Name];
UserList = new List<SelectOption>();
UserList.add(new SelectOption('--Select--','--Select--'));
for(User temp : UserTemp)
{
UserList.add(new SelectOption(temp.Id, temp.Name));
}
return UserList;
}
set;
}
In Test Class
I am calling like this :
List<SelectOption> temp1 = TaskReportingMasterDataIssueController.UserList;
Please do respond !!!!!
Well, as I read your code, I understand you should make multiple test cases and in each one of them provide the corresponding values to issueTeam and query records so that all of the code is executed.
In the test line you have provided you are not including any context so I assume you're missing it in your tests.
My Google-fu is letting me down, so I'm hoping you can help
I'm building some webservices is the play framework using scala and anorm for database access
One of my calls is to update an existing row in a database - i.e run a query like
UPDATE [Clerks]
SET [firstName] = {firstName}
,[lastName] = {lastName}
,[login] = {login}
,[password] = {password}
WHERE [id] = {id}
My method receives a clerk object BUT all the parameters are optional (except the id of course) as they may only wish to update a single column of the row like so
UPDATE [Clerks]
SET [firstName] = {firstName}
WHERE [id] = {id}
So I want the method to check which clerk params are defined and build the 'SET' part of the update statement accordingly
It seems like there should be a better way than to go through each param of the clerk object, check if it is defined and build the query string - but I've been unable to find anything on the topic so far.
Does anyone have any suggestions how this is best handled
As the commenters mentioned it appears to not be possible - you must build the query string yourself.
I found that examples around this lacking and it took more time to resolve this than it should have (I'm new to scala and the play framework, so this has been a common theme)
in the end this is what I implemented:
override def updateClerk(clerk: Clerk) = {
var setString: String = "[modified] = {modified}"
var params: collection.mutable.Seq[NamedParameter] =
collection.mutable.Seq(
NamedParameter("modified", toParameterValue(System.currentTimeMillis / 1000)),
NamedParameter("id", toParameterValue(clerk.id.get)))
if (clerk.firstName.isDefined) {
setString += ", [firstName] = {firstName}"
params = params :+ NamedParameter("firstName", toParameterValue(clerk.firstName.getOrElse("")))
}
if (clerk.lastName.isDefined) {
setString += ", [lastName] = {lastName}"
params = params :+ NamedParameter("lastName", toParameterValue(clerk.lastName.getOrElse("")))
}
if (clerk.login.isDefined) {
setString += ", [login] = {login}"
params = params :+ NamedParameter("login", toParameterValue(clerk.login.getOrElse("")))
}
if (clerk.password.isDefined) {
setString += ", [password] = {password}"
params = params :+ NamedParameter("password", toParameterValue(clerk.password.getOrElse("")))
}
if (clerk.supervisor.isDefined) {
setString += ", [isSupervisor] = {supervisor}"
params = params :+ NamedParameter("supervisor", toParameterValue(clerk.supervisor.getOrElse(false)))
}
val result = DB.withConnection { implicit c =>
SQL("UPDATE [Clerks] SET " + setString + " WHERE [id] = {id}").on(params:_*).executeUpdate()
}
}
it likely isn't the best way to do this, however I found it quite readable and the parameters are properly handled in the prepared statement.
Hopefully this can benefit someone running into a similar issue
If anyone wants to offer up improvements, they'd be gratefully received
Since roughly 2.6.0 this is possible directly with anorm using their macros, http://playframework.github.io/anorm/#generated-parameter-conversions
Here is my example:
case class UpdateLeagueFormInput(transferLimit: Option[Int], transferWildcard: Option[Boolean], transferOpen: Option[Boolean])
val input = UpdateLeagueFormInput(None, None, Some(true))
val toParams: ToParameterList[UpdateLeagueFormInput] = Macro.toParameters[UpdateLeagueFormInput]
val params = toParams(input)
val dynamicUpdates = params.map(p => {
val snakeName = camelToSnake(p.name)
s"$snakeName = CASE WHEN {${p.name}} IS NULL THEN l.$snakeName ELSE {${p.name}} END"
})
val generatedStmt = s"""UPDATE league l set ${dynamicUpdates.mkString(", ")} where league_id = ${league.leagueId}"""
SQL(generatedStmt).on(params: _*).executeUpdate()
producing:
UPDATE league l set transfer_limit = CASE WHEN null IS NULL THEN l.transfer_limit ELSE null END, transfer_wildcard = CASE WHEN null IS NULL THEN l.transfer_wildcard ELSE null END, transfer_open = CASE WHEN true IS NULL THEN l.transfer_open ELSE true END where league_id = 26;
Notes:
The camelToSnake function is just my own (There is an obvious ColumnNaming.SnakeCase available for parser rows, but I couldn't find something similar for parameter parsing)
My example string interpolates {league.leagueId}, when it could treat this as a parameter as well
Would be nice to avoid the redundant sets for null fields, however I don't think it's possible, and in my opinion clean code/messy auto-generated sql > messy code/clean auto-generated sql
I've been trying to add search functionality to my grails project
Here's my domain class
class Resource {
String mimeType
String resourceUrl
String website
static constraints = {
}
}
and here's my controller
class ResourceController {
def report()
{
def website = params.website
println "inside report " + website
def res = Resource.findAllByWebsite(website)
int noOfResources = res.size()
println noOfResources
}
This code works for values of website without any special characters like www.google.com but for some reason whenever there is any special characters in the website valuelike ? or anything, it doesnt fetch anything from the database. Please suggest me an alternate approach.
I tried this as well: def res = Resource.findAllByWebsiteLike(website) but it didn't work too.
Have you tried using a regex search?
such as :
def searchMap
searchMap.put(fieldSearch, [ '$regex' : website, '$options': 'i'] )
def res = Resource.collection.find(searchMap)
I have a little problem filtering data...I have a relation many to many.
Sponsor and Old
I have one intermediary table with both ids...
When I log in, my session save a Sponsor id...but when I go to see Old view, appears every Olds... How to access the intermediary table from the OldController or the SponsorController?
In my Oldcontroller I have:
def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
def sponsor = Sponsor.findById(session.getAttribute("id"))
def myOld = Old.findAllBySponsor(sponsor, params)
def allMyOld = Old.findAllBySponsor(sponsor)
respond myOld, model:[oldInstanceCount: allMyOld.size()]
//respond Old.list(params), model:[oldInstanceCount: Old.count()]
}
But returns unexpected NullpointerException when processing request: [GET] /oldCare/old/index
No value specified for parameter 2.. Stacktrace follows:
Message: No value specified for parameter 2.
How I access the intermediary table for filtering the olds and appears just the Old associated a one Sponsor?
Assuming you have the following :
class Old {
String title
static hasMany = [sponsours: Sponsour]
}
class Sponsour {
String name
static hasMany = [olds:Old]
}
To find :
def sponsor = Sponsor.load(session.getAttribute("id"))
def allMyOlds = Old.findBySponsour(sponsor,params)
I am trying to do a simple case of /author/ and get the Lift to build a Person object based on the id passed in.
Currently i have an Author snippet
class Author(item: Person) {
def render = {
val s = item match { case Full(item) => "Name"; case _ => "not found" }
" *" #> s;
}
}
object Author{
val menu = Menu.param[Person]("Author", "Author", authorId => findPersonById(authorId), person => getIdForPerson(person)) / "author"
def findPersonById(id:String) : Box[Person] = {
//if(id == "bob"){
val p = new Person()
p.name="Bobby"
p.age = 32
println("findPersonById() id = " +id)
Full(p)
//}else{
//return Empty
//}
}
def getIdForPerson(person:Person) : String = {
return "1234"
}
}
What i am attempting to do is get the code to build a boxed person object and pass it in to the Author class's constructor. In the render method i want determine if the box is full or not and proceed as appropriate.
If i change
class Author(item: Person) {
to
class Author(item: Box[Person]) {
It no longer works but if i leave it as is it is no longer valid as Full(item) is incorrect. If i remove the val s line it works (and replace the s with item.name). So how do i do this. Thanks
The Box returned from findPersonById(id:String) : Box[Person] is evaluated and if the Box is Full, the unboxed value is passed into your function. If the Box is Empty or Failure the application will present a 404 or appropriate error page instead.
You can try double boxing your return if you want to handle this error checking yourself (so that the result of this method is always a Full Box).
def findPersonById(id:String) : Box[Box[Person]] = {
if(id == "bob"){
val p = new Person()
p.name="Bobby"
p.age = 32
println("findPersonById() id = " +id)
Full(Full(p))
}else{
return Full(Empty)
}
}
and then this should work:
class Author(item: Box[Person])