I have a grails domain class as below :
class Order {
String orderId = 'OD' + System.nanoTime().toString()
Date orderedDate
String itemName
List bids;
static hasMany = [ bids: Bid ;likedUsers: User,]
static belongsTo =[owner:User]
}
class Bid {
Integer amount
User bidedUser
static belongsTo = [Order]
}
class User {
String username
String password
String emailId
List orders
static hasMany = [orders:Order]
}
What I am trying to do is , to query for an order with bits with maxResult of 10 as like
def critObj = Order.createCriteria()
critObj.list{
eq("id" ,1)
bids {
maxResult(10) //Trying to fetch only 10 records
}
}
How can I load only 10 bits(associations) , is it possible? . Or My design of domain class is wrong?
I think this should work:
def results = Bid.withCriteria {
order {
eq 'id', 1
}
projections {
property 'order'
}
maxResults 10
}
But please note that you have to change your Bid domain class to add the relation in the other way from Bid to Order:
class Bid {
...
static belongsTo = [order: Order]
}
Related
I have two domain classes: User and Book.
class Book implements Serializable{
String bookName
Timestamp createdDateTime
Blob file
static belongsTo = [User]
static hasMany = [user :User]
}
I am able to add user in book using addToUser() method.
But I am stuck in create criteria while applying filter in user.
def query = Book.createCriteria();
def results = query.list () {
eq("user",userObject) // not working since user field is a list of users.
order("createdDateTime", "desc")
}
Please help me with the correct way of filtering.
You need to join the user table first in a many-to-many relation. The criteria should look like:
Book.withCriteria {
user {
eq("id", userObject.id)
}
order("createdDateTime", "desc")
}
I'm not 100% sure how you're trying to model your domain but maybe you want a Book to have a single user? In which case you'd have the belongsTo relationship on Book e.g.
class Book {
String bookName
Timestamp createdDateTime
Blob file
static belongsTo = [user: User]
}
Then have the hasMany relationship on User e.g.
class User {
String name
static hasMany = [books: Book]
}
Then you can look Books up with criteria like:
def user = User.findByName( 'bob' )
def results = Book.createCriteria().list () {
eq( "user", user )
order( "createdDateTime", "desc" )
}
I have a grails application with User and Group domain objects. The User has many Group objects and the Group object contains many User objects:
class User implements Serializable {
static constraints = {
usergroups nullable: true
}
static mapping = {
usergroups cascade: 'all-delete-orphan'
}
static hasMany = [
usergroups: Group
]
static mappedBy = [
usergroups : "creator"
]
}
class Group {
static belongsTo = [
creator : User
]
static hasMany = [
members : User
]
static constraints = {
creator nullable: false
members nullable: true, maxSize: 100
}
}
Given a Group object, can I retrieve the members with max, offset and sortBy parameters? Something like...
def members = User.where {
/* how to specify only the users in 'group.members'? */
}.list(
max: max,
offset: offset,
sortBy : sortBy
);
Edit
To try and fix the problem I have altered the User class to contain a joinedgroups field...
class User implements Serializable {
static constraints = {
usergroups nullable: true
joinedgroups nullable: true
}
static mapping = {
usergroups cascade: 'all-delete-orphan'
}
static hasMany = [
usergroups: Group
joinedgroups: Group
]
static mappedBy = [
usergroups : "creator",
joinedgroups : "creator" // if I don't add this Grails complains there is no owner defined between domain classes User and Group.
]
}
But now when I try to retrieve all the User's usergroup objects in another part of my application only a single usergroup is returned...
def groups = Group.where {
creator.id == user.id
}.list(max: max, offset: offset, sort: sortBy); // should return 3 groups but now only returns 1
This query worked before so maybe adding the extra mappedby entry in User has caused the problem. Is the new mappedby field in User incorrect?
If all the groups that contains a user are saved in the usergroups field, you could use:
def query = User.where {
usergroups { id == myGroup.id }
}
def users = query.list(max: 10, offset: 0, sort : "id")
I have two domains
class ProductQuantity {
Integer quantity
static belongsTo = [productSize: ProductSize]
}
class ProductSize {
String size
static hasMany = [productQuantities : ProductQuantity]
}
I'm trying to build a query where I get all ProductQuantity by the productSize. I have the following query that works.
def productSize = ProductSize.findAllById(1);
def productQuantities = ProductQuantity.findAllByProductSize(productSize)
I'm looking to get the ProductQuanties in a single query rather than two separate queries.
ProductQuantity.createCriteria().list {
eq 'productSize', ProductSize.load(1)
}
or
ProductQuantity.withCriteria {
eq 'productSize', ProductSize.load(1)
}
or
ProductQuantity.where {
productSize == ProductSize.load(1)
}.list()
or
ProductQuantity.findAll("from ProductQuantity where productSize = ?", [ProductSize.load(1)])
Yes, you can get this by createCriteria, like --
def productQuantities = ProductQuantity.createCriteria().list() {
productSize {
eq('id', 1)
}
}
If I have two domain classes like this:
class Company{
string Name
string address
}
class User {
string firstName
string lastName
Company company
}
How can I get all the users from company named Google using criteria query? Something like this:
def company = Company.findByName("Google")
def c = User.createCriteria()
def usersByCompany = c.list {
eq("company", company)
}
You can declare a block inside your closure to filter any field in the Company:
def usersOfGoogle = User.createCriteria().list() {
company {
eq('name', 'Google')
}
}
I just don't remember if it works only for relationships (belongsTo & hasMany), maybe you will need to change your domain class:
class User {
static belongsTo = [company : Company]
}
I have the classes:
class Course{
String name
static hasMany = [
studentGrades: StudentGrade
]
}
class StudentGrade{
String name
int grade
}
How can I make a criteria to get the courses without any student grade?
You could use the isEmpty criterion method:
def c = Course.createCriteria()
def results = c.list {
isEmpty("studentGrades")
}
See the docs for further informations.