Grails domain reload missing attributes - grails

I'm working inside of a service and I have the following two calls:
def user = User.get(2)
user = user.get(1)
This example is contrived, but it illustrates my issue. For the first line I get the user with an id of 2. At this point I have a fully populated domain object and all is well. The fields are populated in the database, so it's not as obvious as missing data. If I call User.get(1)first I'll have a correctly populated domain object. However, when I make the second call (the reassignment) I get a semi populated record. I'm missing the User's firstName, lastName, and email fields. This seems like a pretty simple use case and I've never had this issue in the past. Am I doing something really dumb here? Has something like this happened to anyone else?
Some field definitions:
String username
String emailAddress
String firstName
String lastName
String password
String photoUrl
String title
String contactPhone
Corresponding constraints:
username(blank: false, unique: true)
photoUrl(nullable: true)
title(nullable: true)
contactPhone(nullable: true)
welcomeText(nullable: true)
emailAddress(blank: false, nullable: false)
firstName(blank: false)
lastName(blank: false)

Related

Read Strings from an Object

sorry for this simple question. However, I am confused.
I want to read all Strings from the database.
Basically I am having a EmailSettings emailAddresses = new EmailSettings() object in my controller and want to read all emails saved in the emailSettings Domain object. The class looks like that:
class EmailSettings {
String emailAddress
static constraints = {
emailAddress(blank: false, nullable: false, email: true)
}
}
My problem is I do not get the saved email addresses out of the emailAddresses Object. I tried it with list(), getEmailAddress(like emailAddresses.getEmailAddress().toString(), which is null, even though in the db ARE email addresses saved under this domain object), but it does not work or I get an exception.
Any suggestion how to get the email addresses, which are saved in the db as an array?
I appreciate your answer!
You are creating a new domain instance by newifying it, which will never give you the results that is persisted in db. To get emailAddress from all EmailSettings in db, you can use as:
EmailSetting.all*.emailAdress
or
EmailSetting.withCriteria {
projections {
property 'emailAddress'
}
}
or can also use DetachedCriteria with above projection.
UPDATE
First approach will be expensive because all of the rows will be fetched and then emailAddress from each row will be derived. I totally missed mentioning why I had the second approach with usage of Criteria. Using Projections, you would only get the properties you would need instead of fetching the row itself. Thanks to Graeme.

Grails new Domain(params) initialize results in null field

I did a Google search but came up dry on anything that explained what is happening...
I have the following domain class:
class Company {
Integer companyId
String name
static constraints = {
companyId unique: true
name blank: false
}
String toString(){
return name
}
}
When I do a 'new Company(params)' in the controller with the passed in values, it returns an object with the 'companyId' field set to null. I've double checked the values in 'params' and both 'params.name' and 'params.companyId' are set to non-null values.
What am I doing wrong?
I have another domain/controller (created by someone else now gone) doing something similar that works fine so I must be missing something.
I'm new to Grails/Groovy and any/all advice welcome.

Why some recently added fields are not initialized by constructor

Groovy will all it's dynamic possibilities is still new to me and I'm kind of lost why below code does not work.
def luke = new FooPerson(firstName: "Luke", lastName: "Skywalker", initials: "LS", login: "luke", password: "luke" )
Above gives me proper values for firstName, lastName and initials and for login and password I get null.
If with above code I call
luke.setLogin("luke")
luke.setPassword("luke")
I will get proper value of all fields.
All five fields are declared in class
class Person {
static constraints = {
}
String firstName
String lastName
String initials
String login
String password
}
that my lovely FooPerson inherits from. My problematic fields were not initially in the Person class. I added them recently and obviously this causes groovy some stress.
Of course I can work around this, but I want to understand WHY it's working that weird way.
As noted by #dmahapatro upgrading to grails 2.2.4 solves the problem.
I've looked into release notes of Grails 2.2.4 and I don't see anything meaningful that could be connected to this, but it solves the problem.

Grails: String(username) as primary key, but save and get id string(username) with ignorecase?

I am using a string "username" as the primary-key of a table,
But when saving and getting the column with the username id I want the case to be ignored so that new users can't try to impersonate another user.
e.g. When registering a new user
username = Daxon
username = DaXoN //this should not be allowed
When getting the unique username it can be typed in any case and still be obtained.
Youtube do this with their usernames.
e.g.
youtube.com/user/Daxon
youtube.com/user/DaXoN //Should go to the same profile of 'Daxon' anyway
Domain Class
This uses username as the primary key
class User {
String username
String password
static constraints = {
}
static mapping = {
id generator: 'assigned', name: "username", type: 'string'
}
}
I then scaffold the controllers and views,
so can anyone help me on saving and getting unique usernames with case ignored?
One way you can prevent the second user from registering a name that differs only in case is to create a case insensitive unique index on username at the database layer. If you try to save a name that case-insensitively matches an existing one, you'll get a database exception. This is the default with mysql, but for other databases, something like the following should do it:
create unique index username_csunique_idx on user(lower(username));
I'm not aware of any way to specify that kind of index in the domain class DSL.
To find the objects, query by username case insensitively. For example, User.findByUsernameIlike(userName), or User.find("from User as u where lower(u.username) = ?", [userName.toLowerCase()]) if you prefer HQL.
You can modify your save and get methods of the generated controler to do string comparrisons. Before inserting a username you could do an HQL query that does a case insensitive comparrison on the user name you want to insert to make sure that no user name already exists. See the "HQL And Case Sensitivity" section of the following link. http://dev.wavemaker.com/wiki/bin/view/Dev/HqlTutorial#HCaseInsensitiveQuery

how to validate domain class fields during update in grails

There is domain class with natural key defined as below
class InterestGroup {
String intGrp
String name
static constraints = {
intGrp(blank: false, maxSize: 4, unique: true)
name(blank: false, minSize: 10, maxSize: 50)
}
static mapping = {
id generator: "assigned", name: "intGrp", type: 'string'
}
String toString() { "${intGrp}"}
}
I try to modify standard scaffolding to make possible changes of name field.
In standard code there is save() method called and it checks all field, and of course record could not be updated because record with same key exists. When i just assign field value
interestGroupInstance.name = params?.name
name is updated but, not checked against domain class constaint.
What is the best way to realize CRUD operation with natural keys based tables?
Best regards
Krzysiek
I don't think I'm understanding you. What are you trying to do? You are trying to update your group's name and it doesn't seem to make any validation?
The reference documentaion says: "The save method informs the persistence context that an instance should be saved or updated. The save method returns null if validation failed and the instance was not saved and the instance itself if successful.". So it should be calling validate methos when you call save methos on your domain class object.
Could you please post an example?

Resources