FAQ Database Discussion Community


Grails: Do addTo* and removeFrom* require a call to save?

grails,gorm,grails-2.0,grails-domain-class
In the docs some examples have a call to save whereas some others do not. I'm assuming that addTo* needs the call to save whereas removeFrom* doesn't. Am I mistaken?

Grails findBy query with foreign key

grails,groovy,gorm
I'm trying to fetch a user profile picture from the DB by calling the getProfiePicture() method on User object. Method call from view: <p>${user.getProfilePicture()}</p> User.groovy domain class: class Picture { User user String url boolean profile = false boolean verified = true static belongsTo = [user: User] static constraints =...

Grails hibernate create criteria multiple AND OR Conditions

hibernate,gorm,condition,createcriteria
I was able to do 3 conditions query using grails/Hibernate create Criteria as follows def c = Domain.createCriteria() c.list(max: map.max ?: 10, offset: map.offset ?: 0) { and { "colStatus" in status "code" in codes } and { or { ilike("pCode", pCode) ilike("pDesc", pCode) } } order("DateCol3", "desc") } Now...

Grails findAll closure combine query with hasmany field

grails,groovy,gorm,findall
As per the below Domain Classes VisitSchedules{ Visit visit static hasMany = [users: User] ... } Visit{ DateTime startTime ... } I want to query VisitSchedules for visits that are scheduled for a future date for the user. something like below def upcomingVisitSchedules = VisitSchedules.findAll { visit.startTime >= new DateTime()...

Grails / GORM : org.hibernate.AssertionFailure: null id in xyz (don't flush the Session after an exception occurs)

hibernate,grails,gorm
Edit: got a -1, could you please explain why? I searched for duplicates and did not find any. Posting a Q/A for the issue I just encountered: class Pineapple { def pineappleService Supplier supplier; def beforeInsert() { pineappleService.beforeInsert(this); } } class PineappleService { def beforeInsert(Pineapple pineapple) { Pineapple.withNewSession { //...

Validate() returns false but it has been saved in the database

grails,gorm,spock
I am starting to use grails and I have stumble into a behaviour that I don't understand. Given this domain class class Team { String name Date since Date until static hasMany = [teamMembers:Player] static constraints = { name nullable: false, blank: false, unique: true until nullable: true until(validator: {...

How to show parent domain field in select box in grails

grails,gorm,grails-2.0,grails-domain-class,grails-controller
I am using grails 2.1.0. I need to show a parent domain's field value through parent chain in select box in a gsp page. But I am getting error. So far I have tried as follows :: my first domain which contains parents as named adtAuditPack >>> class AdtAuditorSchdlPack {...

GORM: What is reference:true in Grails domain class mapping block?

grails,gorm,grails-domain-class
public class Address { static mapWith = "mongo" Region region; Zone zone; static mapping = { id generator: 'identity' region reference:true zone reference:true } } I'm interested in knowing what reference:true does. In my experience, leaving it off gives exactly the same result except there's no DBRef in the actual...

Grails 2.4.4 Dynamic One-to-Many Forms

grails,gorm,grails-2.4
I've met an already known old topic that oddly enough is badly documented (if it is even documented). I've been trying to create a dynamic table for a form with a one-to-many relationship in Grails 2.4.4, and for that I had to base myself on a tutorial for 2.1 I'm...

Grails many to many relationship not creating expected tables

hibernate,postgresql,grails,gorm
Hi I have 2 domain classes. The idea is that a User can create events, as well as be a guest at other peoples events: class Event { Appuser creator static belongsTo = Appuser static hasMany = [guests: Appuser] and class Appuser { static hasMany = [friends: Appuser, events: Event]...

grails, pass data from controller to generated _form.gsp view

grails,view,controller,gorm
I got a domain class (Booking) with a User property (using SpringSecurityCore Plugin) and the corresponding views (_form, create, edit, index, show.gsp). A normal user should not be able to set the user the normal way: <g:select id="user" name="user.id" from="${usermanagement.User.list()}" optionKey="id" required="" value="${dailyBookingInstance?.user?.id}" class="many-to-one"/> With this every user can select...

Grails/GORM: No signature of method is is applicable for argument types

grails,gorm
I'm trying to put together a basic blog application using Grails 2.4.4. My domain model is as follows: class Commentable { String title static hasMany = [comments:Comment] } class Comment extends Commentable { static belongsTo = [target:Commentable] } class Post extends Commentable { static hasMany = [tags:Tag] } class Tag...

Cannot get method added to GORM object using AST transformation

grails,groovy,gorm,abstract-syntax-tree
Here is my GORM object @UpdatedProperties class Cart { Date lastUpdated Date dateCreated String name } Here is annotation definition: @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @GroovyASTTransformationClass(["UpdatedPropertiesASTTransformation"]) public @interface UpdatedProperties { } Here is the AST definition @GroovyASTTransformation(phase = CompilePhase.CLASS_GENERATION) class UpdatedPropertiesASTTransformation implements ASTTransformation{ //... public void visit(ASTNode[] astNodes, SourceUnit sourceUnit) {...

Grails - dynamic finders derived date query GORM

grails,groovy,gorm
I have the following domain class class Book { String title Date releaseDate Integer daysOnShelf Author author } How can I list all books where current date is greater than the releaseDate + daysOnShelf? For instance, don't list if 2015-02-10 + 5 (releaseDate + daysOnShelf) since date is less than...

springboot initialization error on startup with mongodb on gorm/groovy

spring,mongodb,groovy,gorm,spring-boot
Getting startup issues for this springboot project using MongoDB/GORM/Groovy on Java 1.7.0_55, gradle 1.11, and spring-boot-gradle-plugin:1.2.1.RELEASE. I'm running the project as-is with the exception of the following change to application.yml for my remote mongodb: spring: mongodb: host: "10.160.8.1" databaseName: "citydb" **On startup, I'm seeing this bean initialization error with mappingMongoConverter...

grails create a list with like query from parent and child domain

grails,gorm,grails-domain-class
I am using grails 2.4.2. I need to create a list based on like keyword of query. Suppose this is an example >> def results = c.list(max: iDisplayLength, offset: iDisplayStart) { and { // eq("activeStatus", ActiveStatus.ACTIVE) } if (sSearch) { or { ilike('title', sSearch) ilike('shortDesc', sSearch) } } } Here,...

Grails - findAll joining two tables

grails,gorm,findall
I'm new to Grails. I'm having problem with retrieving data from DB. I have domains with classes, something like... class Lightbox { String name = '' String link = '' static hasMany = [users: LightboxUserAccount] } class LightboxUserAccount { UserAccount userAccount static belongsTo = [lightbox: Lightbox] } class UserAccount {...

Find instance by name where query is any part of its name, Grails

grails,gorm
In Java, the string search by its' substring goes like this: String string = "Madam, I am Adam"; b = string.matches("(?i).*i am.*"); How to find an instance in Grails by name where query is any part of its name?...

Grails domain class beforeDelete is not working as transactional

grails,gorm
I have an user domain class with attributes like username, fullName, ... etc. and a UserRole association class. In my domain class I have the following code on the beforeDelete method def beforeDelete() { UserRole.removeAll(this); } In the UserRole class I have the removeAll method like this: static void removeAll(User...

Grails query: Get list of associated objects

grails,gorm,hibernate-criteria
I have a many-to-many relationship: class Project { Set<PrincipalInvestigator> pis : static hasMany = [ pis:PrincipalInvestigator ] } class PrincipalInvestigator { String name : } I want a query that returns a unique and sorted list of PIs that belong to a pre-defined list of projects. A naive approach is...

Where is the appropriate place for SQL scripts in a Grails project

grails,gorm
I've got a Grails plugin that exports domain objects so that several applications can share the same schema. We have a few SQL scripts for setting up some complex triggers, views and other functions that just don't really belong in GORM/Hibernate, at least not elegantly. I'd like to store the...

How can I get dateCreated in Has-Many Relation in Grails?

grails,gorm
I have the following domain classes: class A { hasMany = [bs : B] } class B { } Note that B has no backward relation to a. GORM creates a join table in my MYSQL database a_b. This table has two columns the id of a and the id...

findAll exceptions with named parameters

grails,hql,gorm
I'm trying to do a findAll similar to one of the grails examples. This is what I have: def beverage = Beverage.findAll("from Beverage as b where b.id in (:ids)",[ids: [1,2]]) and I'm getting: java.lang.Integer cannot be cast to java.lang.Long ...

Grails GORM domain class with hasMany of same type and duplicate entries

grails,groovy,gorm
In simple terms it's an inventory system, that is tied to SKU's. The SKU is a composite of items, sometimes multiples of the exact same item. E.G SKU for a dining room set would be, 4(Item)"chair" and 1(Item)"table". If I could get GORN to recognize it's tied to multiple instances...

Grails, GORM, update method persists object before calling save()

hibernate,grails,gorm
I have a domain Class DailyBooking and a generated Controller. In the update function I'm calling userService.computeFlexTime(dailyBookingInstance). There I want to get the current persisted entry from DailyBooking (from the database): DailyBooking currentEntry = DailyBooking.findByUserAndDate(dailyBookingInstance.user, dailyBookingInstance.date) From my understanding I should get the current persisted entry from the database because...

How to set the hibernate dialect in Grails 3.0.1

hibernate,grails,gorm
I'm trying out the new Grails 3 stack and I've hit a snag with gorm / hibernate. I have a custom hibernate dialect to support some database features, but the dialect setting in the application.yml file appears to be ignored: dataSource: dialect: "our.namespace.Dialect" pooled: true jmxExport: false driverClassName: "org.postgresql.Driver" username:...

Where are injected domain class methods like isDirty, save, etc defined in Grails / GORM?

grails,gorm
I have a problem where isDirty isn't recognizing that an object has changed, even though I can see very clearly via a debugger that it has. I'd like to take a look at the source, but I can't seem to track the source down, and the debugger won't step into...

Update to grails domain don'tpersist

grails,gorm,grails-domain-class
I'm working in grails 2.3.8 We have the following domain classes: abstract class GroupItem { static belongsTo = [group:AppGroup] static mapping = { tablePerHierarchy = false } } class MyDomain extends GroupItem { String name String type int Identifier static hasMany = [attributes:Attribute] static mapping = { attributes cascade: 'all-delete-orphan'...

Schema Export Errors while launching grails application

grails,gorm
I am trying to follow the Grails application from the book Grails 2 - A Quick start guide. The grails version that i am using is 2.4.4 on Ubuntu 14.04 with the open jdk 7 I am getting the following error Error 2015-03-09 20:05:02,117 [localhost-startStop-1] ERROR hbm2ddl.SchemaExport - HHH000389: Unsuccessful:...

Optimistic Locking Exception using Grails GORM and MySQL

grails,gorm
I am using Grails 2.4.4 and MySQL database. We are trying to clone a group of tables in our database having parent-child relationship. For example we have a table author with its child table book and book having foreign key fk_book pointing to author. We retrieve the hierarchy through Author.get(id),...

Create grails domains from ER-diagram

mysql,grails,gorm
I have the ER diagram. I try describe it like grails domains, but after start project just part of tables exist(created). I can't find in which place I made a mistakes. I use MySQL database, after start only song_tag table crated My grails domains class Song { static hasMany =...

How does one add mongodb and/or postgresql-extension plugins to Grails 3.0.0+?

grails,gradle,gorm,grails-3.0
I played with Grails 3.0.0.M1 today and tried to make a small application using mongodb, however I couldn't manage to add it correctly to my build.gradle file. What is the correct syntax? I tried (excerpt): repositories { mavenLocal() maven { url "http://repo.grails.org/grails/core" } } dependencyManagement { imports { mavenBom "org.grails:grails-bom:$grailsVersion"...

grails method missing exception when trying to find null value in domain

hibernate,grails,gorm
According to the grails doc (found at http://grails.github.io/grails-doc/latest/guide/GORM.html#finders) Category.findAllByParentCategoryIsNull() is the proper way to find a Category who's ParentCategory is null. here's my category domain class class Category { String name Category parentCategory static constraints = { name unique:true parentCategory nullable:true } } for some reason, I'm getting a method...

Sorting on nullable fields in GORM

grails,gorm,grails-3.0
I'm trying to figure out how to sort on multiple fields in Grails 3, one of which may or may not be null. I have this Book domain: class Book { String title String sortTitle static constraints = { title blank: false sortTitle nullable: true } } Books with titles...

Domain class mapping: datasource not working

oracle,grails,gorm,ggts
I have the following domain class that I need to map to a specific datasource (oracle), while all other my domain classes are mapped to the default dataSource (mysql, which works perfectly). My editor is GGTS and as you can notice "datasource" inside mapping appears underlined, as if it were...

Grails how to JSONify domain object including its nested domain classes?

grails,groovy,gorm
I am trying to do one to many domain mapping in grails.Here are the two classes : class TNDetails { String tn String tnpk static hasMany = [iccid: ICCID] static mapping = { table 'ni_tn' version false tnpk column : 'TN_PK' tn column: 'TN' id column: 'TN_PK',name: 'tnpk' } }...

org.hibernate.HibernateException Message reassociated object has dirty collection

session,grails,gorm
I have an application which performs the following steps: Places object in session: def product = Product.get(1) session["product"] = product Performs and Ajax call to update a 1-m relationship, and then renders a partial template which displays the new benefits. These should not yet be saved as the user may...

[B cannot be cast to java.sql.Blob

grails,gorm
This is my domain class class TimesheetSubmission { Date submissionDate=new Date() String foreman String shift String jobId Date date byte[] xmlSubmission String xmlResponse static constraints = { submissionDate nullable: false foreman nullable: false shift nullable: false jobId nullable: false date nullable: false xmlSubmission nullable: true xmlResponse nullable: false } static...

Grails belongsTo multiple classes

grails,gorm,belongs-to
I have a domain class that can belong to one of several classes. I'm seeing validation errors when I try to save. class Teacher { Book book } class Student { Book book } // book can belong to either a student or a teacher class Book { static belongsTo...

To order null values in createcritera.list

grails,gorm
I have a problem when sorting a list created using createCriteria. The problem is when I sort according to some a property its value is null , then the whole object is excluded from the list. (the sort parameter is passed through sorttable column ) Here is a sample of...

Best way to compare lists to fields on a list of objects in Groovy?

grails,groovy,gorm
So I have a list: def list = [1,2,3,...] And then I have a list of objects from the database: def loo = findAllBySomeField() And for each object in the list, if field A on that object doesn't match anything in the first list, then I want to add field...

Grails domain custom validator check uniqueness

grails,gorm
Can you check combination uniqueness of a field inside a custom validator in a Grails domain class? Long points String field1 String field2 Level level level validator {val,obj-> if(obj.points<1000){ //make sure level is unique with field 1 level unique: ['field1'] } else{ //make sure level is unique with field 2...

Subqueries for querying associations in GORM

hibernate,grails,subquery,gorm
I have the following domains in GORM. class Topic { static hasMany = [resources: Resource, subscriptions: Subscription] } class Resource { static belongsTo = [resourceOf: Topic] } class Subscription { static belongsTo = [subscriptionOf: Topic] } I have been unable to find the syntax for running subqueries using criterias/named subqueries....

Grails - what happens with save() if validate on save is false and domain object is invalid?

grails,gorm
What happens if I call save() on a domain object but have set validate: false? if (!domainObject.save(validate: false)) { def errors = "" domainObject.errors.each { errors += it } throw new Exception("Error saving domainObject: ${errors}") } I had though that I would get an exception here as save would return...

What is the correct Grails ORM (GORM) implementation to use?

grails,orm,model,associations,gorm
As a result of a change request I need to implement the correct ORM for my Grails application. I currently have the following simple models and associations: Agent static hasMany = [fees:Fee] Fee static belongsTo = [agent:Agent] However, now I need to implement the ability for a single Fee to...

Deleting the object and its mapping in one-to-many in grails

grails,gorm
I have 2 domain classes as follows - class A { static hasMany = [B] // Just trying to show my mapping } class B { // This table doesn't belongs to A } Now I have a object of class A which contains a set of objects B. I...

Grails: how to programatically bind command object data to domain object in service?

grails,data-binding,gorm
I have a command object that I want to convert into a domain object. However, the object I want to convert the command object into may be one of two domain classes (they're both derived classes), and I need to do it in a service (which is where, based on...

Using like to non-string columns in Grails

hibernate,grails,gorm
I'm currenty working on a Grails query service that involves retrieving row/s from the database with a specific criteria called filterText. List getAdjustmentCodes(params) { def filterText = params.filterText . . . adjustmentCodeList = AdjustmentCode.findAll{ or { ilike('description', "%$filterText%") // ilike('id', "%$filterText%") } } return adjustmentCodeList } Notice that I've comment...

Request via dynamic finders in Grails

grails,gorm
I've three domain classess: class Cafee { String cafeeName static hasMany = [halls: HallsZones] static constraints = { halls nullable: true } } class HallsZones { String hallName static scaffold = true static hasMany = [table : TablePlacesInfo] static belongsTo = [cafee : Cafee] static constraints = { table nullable:...

Grails Executing a query

grails,gorm,hsql
I have a table I make in my app known as Meeting. In Meeting you can choose two people to meet, a string date, and a string location. I want to display the Meetings for each individual coming up soon. So on the index page I have a controller package...

How can this behaviour using a Hibernate query be explained? Is it due to Hibernate lazyness?

hibernate,grails,groovy,gorm,lazy-loading
This morning, I ran into a behaviour i can not really explain : when trying to save (or retrieve if it already exists) some objects with the help of GORM, i was surprised by a NullPointerException when a object (with name "name3") is simply retrieved from the db and stored...

GORM mappedBy and mapping difference

grails,gorm
In the GORM what is the difference between mappedBy and mapping? static mapping = { ... } static mappedBy = { ... } ...

Grails: Is it possible to prevent a domain class instance from being persisted?

grails,gorm
I want to create an (one) instance of a Domain class (which, as expected, has a GORM interface to my database) and only use it as a container to pass data around, like a Map object. I want to make absolutely sure that my instance is never going to get...

Method on class [] was used outside of a Grails application controller

gorm,grails-domain-class,grails-2.3
I have below grails config: Datasource. environments { development { dataSource { dbCreate = "create-drop" // one of 'create', 'create-drop', 'update', 'validate', '' url = "jdbc:h2:mem:devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE" } datasource_staging_oracle { dbCreate = "none" url = "jdbc:oracle:thin:@//myoraclehost:1521/DBNAME" driverClassName = "oracle.jdbc.OracleDriver" username = "username" password = "password" } } Domain class: import org.springframework.integration.Message...

How to get access to properties of related table via WHERE clause?

grails,gorm
For example I have follow domains: class Company { String name } class Employee { String firstName String secondName Company company } And I try to get all employees where company name is 'M$oft' Employee.where { eq 'company.name', 'M$oft' }.list() Got: could not resolve property: company.name of: myapp.Employee Also I...

Grails, custom validator, Hibernate assertion error

grails,gorm
I'm trying to use a service in my domain class for custom validation. In other domain classes this works out pretty well but here I'm receiving a Hibernate assertion error. domain class custom validation: end validator: { val, obj -> if (obj.userWorkingTimeRegulationService.validateit() == false){ return ["error.workingregulation"] } I injected the...

Active Record and Hibernate with GORM

grails,gorm
Coming from a Ruby on rails background I am used to Active Record and running migrations (for almost everything that requires database changes). I understand that Grails is different but how does exactly Hibernate fits in ? So this is how I see things, Active Record (ORM for RoR) =...

Retrieving data using Grails Domain returns with a Class Key by default

grails,gorm
I'm working with a Grails query service and I'm using these the code blocks to retrieve database rows via a domain class. adjustmentCodeList = AdjustmentCode.findAll { or { ilike('description', "%$filterText%") like('id', "%$filterText%") } } adjustmentCodeList = AdjustmentCode.list() adjustmentCodeList = AdjustmentCode.list(max: count, offset: from) It works fine actually, but there is...

Grails DuplicateKeyException / NonUniqueObjectException when batch loading within Async Promise

grails,asynchronous,gorm,promise,batch-processing
I have a large amount of data that I wish to load into a DB using GORM. class DbLoadingService { static transactional = false // these are used to expedite the batch loading process def sessionFactory def propertyInstanceMap = org.codehaus.groovy.grails.plugins.DomainClassGrailsPlugin.PROPERTY_INSTANCE_MAP // these are example services that will assist in the...

Grails use inherited property within named query

hibernate,grails,gorm,named-query
I want to use an inherited property within a named query of a derived instance, in order that I can provide a custom sort of the results. I am getting an error. package com.example class Ticket { // User is defined elsewhere static belongsTo = [user : User] String idNumber...

Is it possible to save a specific id for a grails domain object?

grails,gorm
I am in the process of trying to copy the properties of one domain object to another similar domain object (Basically moving retired data from an archive collection to an active one). However, when I try to save with a manually inputed id the save will not actually put anything...

Named query on child joining two levels of parent tables

grails,gorm
Given class Store { String name static hasMany = [departments: Department] } class Department { String name static belongsTo = [store: Store] static hasMany = [products: Product] } class Product { String name Integer qty static namedQueries = { productsInStockByStore {store-> department { store { eq 'id', store.id } }...

How to delete a child domain row in grails

oracle,grails,gorm,grails-2.0,grails-domain-class
I am saving data to my entry meeting table as well as entry meeting details table which is a child table of entry meeting table. But When I want to delete only a child table record it's giving a error. I can't understand what to do. I am using grails...

Conversion: datetime to time

grails,gorm
I am working on legacy database in which there is a table having time as its data type but In Grails when we define a field of type Date then it generates a field of type datetime, is there any way to give instruction in domain so that it generate...

How to implement batch processing in Grails

grails,gorm,batch-processing
I have a Grails application which implement multiple datasource and its task to process and save excel data(xlsx type) in corresponding datasource tables. But I got a problem when excel file contains huge data and it taken more time to save. So I have used SQL and insert values through...