A domain Staff has a User.
class Person {
User user
}
class Staff extends Person {
//other properties
}
class User {
String username
String password
}
I know a user logged in, now I want to find the Staff by the same logged in User. No relation is maintained from User's side.
The code I am implementing is :
def createdBy = User.get(springSecurityService.principal.id)
log.info("User id : "+createdBy.id) // it works
def staff = Staff.findByUser(createdBy) //it returns null
Is this not applicable in GORM or I'm missing something?
grails findBy documentation has nothing to tell about findByDomain().
The question is CLOSED as the error was while inserting a Staff with a User which was not heppening in proper way.(poor grails didn't notify me.)
Above code works perfectly.
def createdBy = User.get(springSecurityService.principal.id)
def staff = Staff.findByUser(createdBy)
But, meanwhile implemented another way of finding Staff in criteria way :
def createdBy = User.get(springSecurityService.principal.id)
def staff = staffCriteria.get{
user{
idEq(createdBy.id)
}
}
Related
I have two domains, Patient and Allergy. I want to save allergies particular to the specific patient(email is the unique identifier for each patient). The details are coming from an android app and email is one of the parameters.
Assuming a user already exists, how would I go about the allergy service to be able to do this.
This is the patient service which successfully registers a new patient and saves their details. I have a controller which acts as an API for the android app.
#Transactional
class PatientService {
//creating new
def updateSave(params) {
def patient
//record exists
if(params.id){
patient = Patient.findById(params.id)
if(patient) {
patient.validate()
patient.dateUpdated = new Date()
patient.save(params)
}
}else{
params.password=MD5CodecExtensionMethods.encodeAsMD5(params.password)
patient = new Patient(params)
patient.validate()
System.out.println(patient.errors)
patient.save flush:true
}
return patient
Here is what I have tried with allergy service but am stuck
#Transactional
class AllergyService {
def Save(params) {
def allergy
Patient patient
allergy = new Allergy(params)
allergy.validate()
System.out.println(allergy.errors)
allergy.save flush:true
return Allergy.findAllByPatient(params)
}
I am assuming that the Patient has many Allergies, so you have to create an appropriate association:
class Patient {
static hasMany = [allergies: Allergy]
}
class Allergy {
}
Grails will automatically inject a Set of allergies into the Patient domain.
In your save method, you should have access to Patient or his email property in order to connect them somehow.
Then, you can do like:
def save(patientEmail, params) {
Patient patient = Patient.findByEmail(patientEmail)
Allergy allergy = new Allergy(params)
patient.addToAllergies(allergy)
patient.save()
}
These are my domain objects
User{
hasMany = {roles: UserRole}
}
UserRole{
User user
Role role
}
Role{
String authority
}
I need to find users based on their Role. For that I am trying to use the following criteria:
def role_admin = Role.findByAuthority('ROLE_ADMIN')
def criteria = new DetachedCriteria(User).build {
roles{
role{
idEq(role_admin.id)
}
}
}
result.users = criteria.list(params)
result.total = criteria.count()
The above will always return one result, even though I have verified by looking at the database directly that there should be more results. The params passed to list are correct, but I tried removing them just to be sure. I can't see what is wrong with the above, any suggestions ?
I also tried this
roles{
role{
eq("authority","ROLE_ADMIN")
}
}
But it is throwing exception:
Unknown column 'role_alias2_.authority' in 'where clause'
this works for me:
def criteriaUsers = UserRole.createCriteria()
def users = criteriaUsers.listDistinct{
eq("role", role_admin)
}.user
Side note: from the nomenclature of your classes it looks like you are using spring-security-core plugin. In my humble opinion the hasMany = [roles: UserRole] is redundant as the association User - Role is already being modeled in the UserRole class.
My web interface has an ajax call to update a photo's caption. A post sends the caption and the publicId of the photo to a service.
The service has
Photo photo = Photo.findByPublicId(params.publicId)
photo.caption = params.caption
photo.save()
However I have read in Burt Beckwith's grails book this is not secure. As-is a hacker could post any publicId to my service and update the
caption of a photo that doesn't not belong to their session. I need some GORM advice on how to write the update query to update only photos belonging
to the current user's session. Due to the number of joins involved I am lost. I am familiar with getting the profile/user:
User user = User.load(springSecurityService.principal.id)
Profile profile = Profile.findByUser(user, [lock:true])
but not the one query that would join everything for the entire update, instead of Profile.findByUser(user, [lock:true]).photoAlbum.getPhotoWherePublicId(publicId) or something that seems it would make 4 different sql calls.
The domain schema I have with the hierarchy in question is :
//user from springsecurity for session/login management
class User {
//no reference to profile
}
class Profile {
PhotoAlbum photoAlbum
User user //reference to user
static constraints = {
photoAlbum(nullable:true)
}
}
class PhotoAlbum {
static hasMany = [photos:Photo]
static belongsTo = [profile:Profile]
}
class Photo {
static belongsTo = PhotoAlbum
String caption
String publicId
}
Maybe with a criteria or namedQuerie this could be done.
Something like this may work:
First make a small change to your Photo class
class Photo {
PhotoAlbum photoAlbum
static belongsTo = [photoAlbum: PhotoAlbum]
String caption
String publicId
}
and try with this criteria
Photo.withCriteria{
eq 'id',params.publicId
photoAlbum {
eq 'profile',profile
}
}
I am using springSecurityCore plugin in my application and after user login in the appStartupController, I do like
def index = {
if (springSecurityService.isLoggedIn()) {
session.loginId=springSecurityService.principal.id
def userRole=UserRole.findAllByUserAndRole(User.get(session.loginId), Role.findByAuthority('ROLE_USERSDASH'))
if(userRole){
redirect(controller:'dashboard',action:'getRiskUserDashboard')
}
}
}
when I read session.loginId in the header.gsp I see the firstname from the User table is printed.
I need to have the userId field in the User table mapped to the session.loginId.
How to do that?
You can get the current User by calling the following:
def user = springSecurityService.getCurrentUser()
And then just pass that user into the UserRole find method.
I have a User class which has a List field namely pt. This field is not initialized when User register his account. But when user goes this controller action :
def updatePt() {
//performs some action
def user = User.get(springSecurityService.principal.id) //find the user
user.pt = []
//on certain conditions i put values into user.pt like this
user.pt << "E"
//at last I save it
user.save()
}
But using user/show action via scaffolding I found that pt field is not saved on users object. Where I'm making a mistake?
You have to provide a static mapping in the Users domain class so that Grails knows the field must be persisted:
class User {
static hasMany = [pt: String]
}
It's possible because of validation error. Try with
if (!user.save()) {
log.error('User not saved')
user.errors.each {
log.error('User error: $it')
}
}
PS or you can use println instead of log.error