Assigned domain class id wierdness with Grails - 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 :-)

Related

Property xxx is type-mismatched

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

How to pass a string in findById(String id) Grails

How to use a String value as a parameter in findById(), It always expecting a Long value. Iam using a domain class named Employee and I configured its id key as string. But still Employee.findById() is expecting a long value as parameter.
Please help me
My Employee.groovy
class Employee {
static hasOne = [user:User, vpn:Vpn, tenrox:Tenrox, machine: Machine, dbuser:DbUser];
static mapping = {
version false
id generator: 'assigned',type: 'string'
}
String name
String designation
String team
Long contact_no
static constraints = {
name(nullable: false,maxSize:100)
designation(nullable: true,maxSize:40)
team(nullable: true,maxSize:40)
contact_no(nullable: true,maxSize:20)
}
}
Declare your id field in the domainclass as String.
class Employee {
static hasOne = [user:User, vpn:Vpn, tenrox:Tenrox, machine: Machine, dbuser:DbUser];
static mapping = {
version false
id generator: 'assigned',type: 'string'
}
String id // Declares id as String
String name
String designation
String team
Long contact_no
static constraints = {
name(nullable: false,maxSize:100)
designation(nullable: true,maxSize:40)
team(nullable: true,maxSize:40)
contact_no(nullable: true,maxSize:20)
}
}

Cannot redirect for object [ManageVehicle : (unsaved)] it is not a domain or has no identifier. Use an explicit redirect instead

This is my domain.
import org.apache.commons.lang.builder.EqualsBuilder
import org.apache.commons.lang.builder.HashCodeBuilder
class ManageVehicle implements Serializable {
String vehicle
Short truckKey=0
Short siteID
Integer unitID
String wheelConfig
String model
Short period=0
String usid=UUID.randomUUID().toString()
//static belongsTo = [wheelConfig : TTType,model:TTModel]
int hashCode() {
def builder = new HashCodeBuilder()
builder.append truckKey
builder.append siteID
builder.toHashCode()
}
boolean equals(other) {
if (other == null) return false
def builder = new EqualsBuilder()
builder.append truckKey, other.truckKey
builder.append siteID, other.siteID
builder.isEquals()
}
static mapping = {
table 'TF_Truck'
version false
truckKey column :'TruckKey'
siteID column :'SiteID'
id composite:['truckKey','siteID']
vehicle column: 'TruckID' ,sqlType: 'nvarchar'
wheelConfig column: 'TypID',sqlType: 'tinyint'
model column: 'ModID' ,sqlType: 'tinyint'
unitID column: 'McmID',sqlType: 'tinyint'
period column: 'Period'
usid generator: 'assigned', column:'USID', sqlType:'uniqueidentifier'
}
static constraints = {
period nullable: false
truckKey nullable: false
siteID nullable: false
}
}
And my save method in controller is .
def save(ManageVehicle manageVehicleInstance) {
manageVehicleInstance.siteID=RequestContextHolder.currentRequestAttributes().getAttribute("SiteID",RequestAttributes.SCOPE_SESSION) as Short
if (manageVehicleInstance == null) {
notFound()
return
}
if (manageVehicleInstance.hasErrors()) {
respond manageVehicleInstance.errors, view:'create'
return
}
manageVehicleInstance.save(flush:true,failOnError: true)
request.withFormat {
form {
flash.message = message(code: 'default.created.message', args: [message(code: 'manageVehicle.label', default: 'Manage Vehicle'), manageVehicleInstance.id])
redirect manageVehicleInstance
}
'*' { respond manageVehicleInstance, [status: CREATED] }
}
}
while i am applying save operation on this domain i am getting following exception .
Message: Cannot redirect for object [ManageVehicle : (unsaved)] it is not a domain or has no identifier. Use an explicit redirect instead
Suggest me some solution.
I guess that Grails cannot handle composite id in redirection.
I have two options in my mind to fix that case
Create id field for your domain class by removing id line from mappings
Implement custom redirection for your saved object like
redirect(action:'show', params:[truckKey:manageVehicleInstance.truckKey,siteID:manageVehicleInstance.siteID])
With 2. option you may also have to implement custom object loading into 'show' action using composite id like def manageVehicleInstance = ManageVehicle.findByTruckKeyAndSiteID(params.truckKey, params.siteID).

Grails: Legacy DB - Record with composite Id won't update

I'm having problems trying to update a record on a Grails 2.3.7 Project
I don't want to modify the fields that are part of the composite Id, I just want to update the other fields.
Just one class, few properties, but every time I try to update, it throws me the "not unique error" when this lines runs:
personInstance.validate()
if (personInstance.hasErrors()) {
respond personInstance.errors, view:'create'
return
}
My class looks like this:
class Person implements Serializable {
static constraints = {
name(unique: lastName)
}
static mapping = {
id generator: 'assigned'
id composite: ["name", "lastName"]
}
//Override equals and hashcode methods
boolean equals(other) {
if (!(other instanceof Person)) {
return false
}
other.name == name && other.lastName == lastName
}
int hashCode() {
def builder = new HashCodeBuilder()
builder.append name
builder.append lastName
builder.toHashCode()
}
String name
String lastName
String description
}
And the controller action:
def update() {
def personInstance = Person.get(new Person(name:params.name, lastName:params.lastName))
personInstance.properties = params
personInstance.validate()
if (personInstance.hasErrors()) {
respond personInstance.errors, view:'create'
return
}
personInstance.save flush:true
request.withFormat {/*etc...*/}
}
When I use validate(), it throws me a Grails unique key error, when I avoid validation its a BD not unique PK error.
Is like Grails didn't know if I want to do an insert or an update when I personInstance.validate().
Is there a way to manage this in a correct way that I'm not seeing?
Or am I forced to avoid validation?
am I doing something wrong?
Thanks in advance.
I believe the GORM mapping DSL expects just one id definition. Try combining your two id lines into just this one:
id generator: 'assigned', composite: ["name", "lastName"]
Also, in addition to implementing Serializable, your domain class should override equals and hashCode, as described under "Composite Primary Keys" here: http://grails.org/doc/latest/guide/single.html#identity

How to map Domain Object Properties to Columns

I have this domain class.
class Book {
String code
String description
static mapping = {
table 'Book'
version false
}
}
and I have table BookStore with columns COD and DSC.
I need map to this table.
How can I achieve this?
If I understand your question correct, the sections within Mapping in the documentation should help you
For your example, the following should work:
class Book {
String code
String description
static mapping = {
table 'BookStore'
version false
code column: 'COD'
description column: 'DSC'
}
}
Also, within DataSource.groovy, make dbCreate = "update" under the appropriate environment that you are using. Refer the documentation on DataSource for this.
Hope this helps.
class Book implements Serializable {
String code
String description
static mapping = {
table 'BookStore'
version false
id composite: ['code']
code column: 'COD'
description column: 'DSC'
}
boolean equals(other) {
if (!(other instanceof Book)) {
return false
}
other.code == code
}
int hashCode() {
def builder = new HashCodeBuilder()
builder.append code
builder.toHashCode()
}
}

Resources