I am new to Grails , I have some issue as stated below.
I have 2 domain classes : Parent and Child. I am storing arrays of arrays into database.
Parent class is :
class Parent{
static hasMany = [child: Child]
}
Child class is :
class Child {
String time
String record
String value
static belongsTo= [parent: Parent]
static constraints = {
time(blank: false)
record(blank: false)
belongsTo(blank: false)
}
}
Now my requirement is :
I need to retrieve the child's latest records that contain multiple rows in the database with unique parent id.
e.g : Parent's latest id is 7.
Child table contains nearly 10 records on parent id 7. I want to retrieve all these 10 records with the reference of the parent id(7).
Please some one help to write a code/query .
gorm is a greate ORM you could use following:
def parent = Parent.get(7)
def childList = Child.findAllByParent(parent);
read this, it'll help you to understand gorm better.
Related
Can anyone please help me.I have two domains.
Class Parent{
static hasMany = [child: Child];
}
Class Child{
}
In database there are 20 records.I want to get 10 records only without refreshing the page.So i used remote pagination like.
gsp code is
<util:remotePaginate controller="Parent" action="show"
total="${parentList.size()}"
update="updatedListId" max="10" pageSizes="[10, 20, 50,100]"/>
In Controller i wrote like.
def parent =Parent.get(1);
def parentList = parent.getChild();
I tried this one but its is not working.
def childs = Child.findAllByParent(parent, [max: 10])
It is giving all records but i need to here get only 10 records. I set params max value and pass it as argument but its not working.
please help me.
thanks
You can get the childs in a join via HQL:
Child.executeQuery("select c from Parent p join p.childs c where p=:p", [p:p, max:10])
Have you tried where query?
// Parent.groovy
class Parent{
static hasMany = [ children: Child ]
}
// Where query in controller/service
Parent.where { id == 1L }.children.list(max: 10)
Hi I'm trying to perform a sort in a controller of parent and child before rendering a json file but I'm not sure how to go about doing it. Here's what I have (excerpt of original code):
class Parent{
static hasMany = [children:Child]
String name
Date dateCreated
}
class Child {
static belongsTo = [parent:Parent]
String name
Date dateCreated
}
In my controller .groovy file I have :
def list(){
def result = Parent.listOrderByDateCreated(order: "desc")
.... more code ....
withFormat{
json {render result as JSON}
xml {render result as XML}
}
}
and the above works (parent is sorted by date created) but I'm not sure how can I sort all the children by date created within the list.
Thank you for your help in advance. Also I'm using Grails 2.3.2
One way is to assume you always want the children sorted by the dateCreated. Add the following to your Parent domain:
static mapping = {
children sort: 'dateCreated'
}
Another way would be to do the sort after you've pulled the results:
def sortedChildren = parent.children.sort { it.dateCreated }
If there is a fancier "grailsier" way to do this via finders or criteria, I do not know.
I have the following domain classes
class Child{
def age
}
class Parent{
static hasMany = [children:Child]
}
and I would like to execute the following in HQL
Parent.list()
.sort{ parent -> parent.children.sort{ child -> child.age}[0]}[0..10]
Basically I would like to retrieve a list of parents sorted by the age of their eldest child. And restrict this to only 10 records. I don't want to pull all parent and child records from the database, and then do the necessary sorting. I was hoping that HQL could do this on the 'database layer', and only return the results I need. Thanks :)
Parent.withCriteria {
createAlias('children', 'ch', org.hibernate.criterion.CriteriaSpecification.LEFT_JOIN)
order("ch.age", "desc")
maxResults(10)
setResultTransformer(org.hibernate.criterion.CriteriaSpecification.DISTINCT_ROOT_ENTITY)
}
I'm new to Grails&GORM so this may be a quick question. We are currently looking at using GORMs mongo support and I am having a few issues mapping to existing collection data. I basically want to map to a hierachical object structure whereby my object "Merchant" has reference to another parent merchant. The BSON structure is fairly simple i.e.:
{
name: "name",
parent_id: ObjectId("[Object Id ref]")
}
In my model I attempted to map this relationship as follows:
class Merchant {
ObjectId id
String name
Merchant parent
static belongsTo = [parent: Merchant]
static mappedBy = [parent: "parentId"]
static mapping = {
collection "merchants"
}
static constraints = {
}
}
This resulted in the following BSON:
{
"_id" : ObjectId("4ea6be91ce5f56cd49f43ab8"),
"name" : "where will you g",
"version" : NumberLong(1),
"parent" : {
"$ref" : "merchants",
"$id" : ObjectId("4ea6be91ce5f56cd49f43ab8")
}
}
This has two issues, namely:
- The name of the parent merchant field is "parent" and not "parent_id", which is required.
- The value of the parent field has additional meta infomation other than the id in i.e. $ref : "merchants".
Is there anyway I can keep our existing BSON structure and still have a rich object mapping.
Cheers, Chris.
For the two issues, you need an additional mapping:
static mapping = {
collection 'merchants'
parent attr:'parent_id', reference:false
}
You should also drop the mappedBy block, since you only need it when there are multiple fields of the same type.
Finally, note that reference:false is the default in recent versions of the plugin (1.2+ I think). Note that 'attr' is named 'columnName' in other flavours of GORM.
Grails 1.1.1
Goovy 1.5.7
In a relationship such this:
Author 1 -- n Book n -- 1 Publisher
Defined in Grails:
class Author {
String firstName
String lastName
static hasMany = [books: Book]
static constraints = {
books(nullable: true)
}
}
class Book {
String title
Author author
Publisher publisher
static constraints = {
author(nullable: true)
publisher(nullable: true)
}
}
class Publisher {
String name
static hasMany = [books: Book]
static constraints = {
books(nullable: true)
}
}
I want to load a Book with the values of Publisher and Author.
When i get a Book with the query:
def book2 = Book.findAllByAuthor(author)
I get the response with the autor assosiated but the publisher only have the id and name class in the other query:
def book3 = Book.findAllByPublisher(publisher)
I retrieve me the inverse result,i have the book with the publisher data but the author only have the id and the class name.
Where is the error in the defined model ? o there is an error in the way to do the queries ?
Edit:
I need the way to retrieve the values only with the query like this:
def book2 = Book.findAllByAuthor(author, [fetch:[publisher:'eager']])
In this one I can manage the value of publisher.
Question: If publisher had a hasmany or Domain related, getting the book I'm able to read the attributes?
Thanks.
Thanks.
Lazy fetching is used by default with gorm associations. If you want to enable eager fetching, you can modify the ORM DSL by adding the following mappings block to your Author domain class:
static mapping = {
books lazy:false
}
or you could change the fetch mode in the domain object by adding following code after your books relationship is defined.
static fetchMode = [books:"eager"]
Doing the same to your Publisher domain object should allow you to accomplish what you want. You do want to be careful of the consequence that you may load more data than you intend to.
Shouldn't the get() method return what you are looking for?
Example: def book2 = Book.get(author)
You'd better use Criteria and explicitly define which relations should be loaded eagerly. Just mention relation in the query.
Example:
def c = Teacher.createCriteria()
List<Teacher> results = c.list {
subjects {
attendees {}
}
}