Property xxx is type-mismatched - grails

I'm trying to build simple CRUD application using Grails. I'm absolutely new to this framework. My CRUD table has few properties, connected to a local database and it works so well except it can't load pictures in it. I get a error that it's type mismatched. How to solve it?
My controller class is below:
class Person
{
int id
String name
String address
byte[] profilePic
}
static constraints
{
profilePic maxSize :204800
}
static mapping
{
table 'all_users'
version false
columns
{
id column: 'id'
name column: 'name'
address column: 'address'
profilePic column: 'profilepic'
}
}

Domain Code
class Person
{
int id
String name
String address
String profilePic
}
static mapping
{
table 'all_users'
version false
columns
{
id column: 'id'
name column: 'name'
address column: 'address'
profilePic column: 'profilepic'
}
}
Controller Code
def save(){
def person = new Person(params)
person.save flush: true, failOnError: true
redirect action: "show", id: person.id
def downloadedfile= request.getFile('profilePic')
String profilePic = "D:/Your Grails Applications/grails-app/assets/images/" + person.name + ".jpg"
downloadedfile.transferTo(new File(profilePic))
}
View Code
<input type="file" name="profilePic"/>

Take a look http://docs.grails.org/latest/guide/single.html#uploadingFiles and How to store a file in the database with Grails

Related

How to convert native sql to grails/gorm

Can I convert this to GRAILS/GORM. If yes, any help please.
select b.id, b.username, b.first_name, b.last_name
from tb_user_orgpermissions a
inner join tb_user b on a.username = b.username
where
(a.department_id = :dept_id)
and (a.agency_id = :agy_id)
To create the equivalent query as a gorm criteria query, the first thing you need is domain classes (with proper associations) for each table. As an example, here's some pseudo code:
class User {
String username
String firstName
String lastName
static hasOne = [permission: UserPermission]
}
class UserPermission {
Department department
Agency agency
}
class Department {}
class Agency {}
In this example User has a one-to-one association to UserPermission.
With something like this in place you can create a criteria query (with projections):
User.withCriteria {
projections {
property 'id'
property 'username'
property 'firstName'
property 'lastName'
}
permission {
department {
eq 'id', dept_id
}
agency {
eq 'id', agy_id
}
}
}

Grails 2.1 Join Query

I m new user in Grails. I don't know how to write projection query. Here is my code. please anyone help me for grails projection query.
From Join table I want to find username which is consist in user table
Given the following example domains:
class User{
transient springSecurityService
String username
String password
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static mapping = {
table 't04t001'
id column: 'f_account_id'
username column: 'f_username', length: 10
password column: 'f_password', length: 100
enabled column: 'f_account_active'
accountExpired column: 'f_account_expired'
accountLocked column: 'f_account_locked'
passwordExpired column: 'f_password_expired'
version column: 'f_revision'
}
}
class Role{
String role
static mapping = {
table 't04t003'
id column : 'f_role_id'
role column : 'f_role'
version column : 'f_revision'
cache true
}
}
class UserRole implements Serializable {
User user
Role role
static mapping = {
table 't04j002'
id composite : ['role', 'user']
role column :'k_role_id'
user column :'k_user_id'
version false
}
}
I can't figure out how to build the criteria to find all the user. I tried the following:
def criteria = UserRole.createCriteria()
def list = criteria.list {
projections {
user{
ilike('username', 'omar')
}
}
}
In console mode i have seen this query with message
Hibernate:
select
this_.k_role_id as k1_3406_0_,
this_.k_user_id as k2_3406_0_
from
t04j002 this_
where
(
lower(user_alias1_.f_username) like ?
)
However, it says Unknown column 'user_alias1_.f_username' in 'where clause'.
But i cant figure out this(user_alias1_) alias
I am not exactly clear on what you want to retrieve from which table. So based on your criteria query, here is how to retrieve user from the UserRole table.
def criteria = UserRole.createCriteria()
def result = criteria.list {
projections {
property("user")
}
user {
eq("username", "omar") //strict match
}
}
return result;
What this does is it builds a list that has the user.username as omar. By default the result will be the UserRole object, but to get user object instead we used projections.
Update:
Your Domain class seems a bit out of grails conventions. Why not user something like this?
//User.groovy
class User {
String username
// ..
static constraints = {
username blank: false, nullable: false, maxSize: 10
}
}
//UserRole.groovy
// Since you are using composite keys, we have to implement serializable. But is there a need for composite key in your situtation?
class UserRole implements Serializable {
User user
// ..
}
In you service class
// UserRoleService.groovy
def getUser(String username) {
def criteria = UserRole.createCriteria()
def result = criteria.get {
projections {
property("user")
}
user {
ilike("username", username)
}
}
return result;
}
And to call the service method from controller,
// ExampleController.groovy
class ExampleController {
def userRoleService
def index() {}
def someThing(String username) {
def user = userRoleService.getUser(username)
println user?.username
// ..
}
}

Gorm change primary key, not found with id null

I have read tons of questions about this and it seems that nobody gets it to work.
I am using grails, and I am creating a class that doesn't have id as the primary key.
I get the message "usuario not found with id null". this is the code of my domain class:
class Usuario implements Serializable{
String nombre
String celular
String telefono
String apellido
String password
String nick
static mapping = {
table 'Usuarios'
version false
id composite: ['nick']
}
}
I also tried the normal way with the:
static mapping = {
table 'Usuarios'
version false
id name: 'nick'
}
It actually maps the table the way I want to with the natural key and everything, it inserts the new usuarios, but the gui is incapable of retrieving any objects and shows the error: "usuario not found with id null"
I tried to modify the show(Long id) method, but it wont help either, this is my show method from the controller:
def show(String nick) {
def usuarioInstance = Usuario.get(nick)
if (!usuarioInstance) {
flash.message = message(code: 'default.not.found.message', args: [message(code: 'usuario.label', default: 'Usuario'), nick])
redirect(action: "list")
return
}
[usuarioInstance: usuarioInstance]
}
You need to specify the assigned generator:
static mapping = {
...
id column: 'nick', generator: 'assigned'
}
Plus it might be wise to add the following constraints:
static constraints = {
nick blank:false, nullable:false, unique: true
}

How to save associated object in Grails?

I am a grails beginner.
i have a 2domain class
class Employee {
String name
String department
static constraints = {
}
public String toString() {
name
}
}
class Address {
String line1
String line2
Employee employee
static belongsTo = Employee
static constraints = {
}
}
where Address belongs to Employee .. so i have given belongsTo association.
My Employee/create.gsp page takes input for fields specified in Employee and Address.
so on creation of employee , address must be get save automatically .
so what could be the save action in EmployeeController
i have tried some thing like this but did not work.
def save = {
def employeeInstance = new Employee(params)
def addressInstance = new Address(params)
if (employeeInstance.save(flush: true)) {
flash.message = "${message(code: 'default.created.message', args: [message(code: 'employee.label', default: 'Employee'), employeeInstance.id])}"
redirect(action: "show", id: employeeInstance.id)
}
else {
render(view: "create", model: [employeeInstance: employeeInstance])
}
}
how to save this associated model ?
Here you have a one-to-one relationsip - add an address property to the Employee class.
class Employee {
String name
String department
Address address
public String toString() {
name
}
}
Change your belongsTo of the Address like this:
class Address {
String line1
String line2
static belongsTo = [employee: Employee]
}
Now you could create an Employee like this:
def employeeInstance = new Employee(params)
employeeInstance.address = new Address(params)
if (employeeInstance.save(flush: true)) {
// your logic
}
Read the docs (one-to-one relationship) for further informations.

Assigned domain class id wierdness with Grails

I want to set the id manually on grails 1.3.7
This compiles but the id is always 0
//in bootstrap
def it1 = new ItemType(id:4,name:'feature')
it1.save()
//domanin class
class ItemType {
String name
int id
static constraints = {
id(unique:true,blank:false)
name(blank:false)
}
static mapping = {
id column: 'ItemTypeId', generator:'assigned'
name column: 'Name'
version false
}
}
This compiles and id 4 (as required)
//in bootstrap
def it1 = new ItemType(name:'feature')
it1.id=4
it1.save()
//domanin class
class ItemType {
String name
//int id
static constraints = {
id(unique:true,blank:false)
name(blank:false)
}
static mapping = {
id column: 'ItemTypeId', generator:'assigned'
name column: 'Name'
version false
}
}
So my question is there a way to have id as prop but assigned?
Had the same problem a few days ago: my own id in GORM
It seems that it is a feature :-)

Resources