I have a domain classes like so:
class Person {
Team team
static hasMany = [history: PersonHistory]
}
class PersonHistory {
Team team
Person person
}
Now I would like to create a criteria that pulls back all the 'persons' who have a PersonHistory instance with a different team.
Something along the lines of:
def c = Person.createCriteria()
def experiment = c.list {
history {
neProperty("team", history.team)
}
}
However this is throwing (because of the history.team):
Missing Property Exception
No such property: history for class: grails.orm.HibernateCriteriaBuilder
Can I do this inside one criteria query? If so, how?
I haven't test it but I think this should work:
Person.withCriteria {
createAlias 'history', 'h'
ne 'team', h.team
}
You have to create an alias for the join with history.
EDIT:
Now I got it! With the following sample data:
def t1 = new Team(name: 'team 1').save()
def t2 = new Team(name: 'team 2').save()
def t3 = new Team(name: 'team 3').save()
def p1 = new Person(team: t1).save()
def p2 = new Person(team: t1).save()
def p3 = new Person(team: t2).save()
def p4 = new Person(team: t2).save()
def p5 = new Person(team: t3).save()
def ph1 = new PersonHistory(person: p1, team: t1).save()
def ph2 = new PersonHistory(person: p2, team: t3).save() // t3 instead of t1
def ph3 = new PersonHistory(person: p3, team: t2).save()
def ph4 = new PersonHistory(person: p4, team: t1).save() // t1 instead of t2
def ph5 = new PersonHistory(person: p5, team: t3).save(flush: true)
Now you can execute the following criteria:
List<Person> persons = PersonHistory.withCriteria {
createAlias 'person', 'p'
neProperty 'p.team', 'team'
projections {
property 'person'
}
}
That will return the correct persons p2 and p4
Related
Taking inspiration from this post:
How can I present a many-to-many relationship using a link table with ScalaQuery or SLICK?
My situation is a somewhat the same with some small exception.
def testManyToMany(): Unit = db withSession {
object A extends Table[(Int, String)]("a") {
def id = column[Int]("id", O.PrimaryKey)
def s = column[String]("s")
def * = id ~ s
def bs = AToB.filter(_.aId === id).flatMap(_.bFK)
// note I have another many-to-many join
def cs = AtoC.filter(_cId === id).flatMap(_.aFK)
}
object B extends Table[(Int, String)]("b") {
def id = column[Int]("id", O.PrimaryKey)
def s = column[String]("s")
def * = id ~ s
def as = AToB.filter(_.bId === id).flatMap(_.aFK)
}
object AToB extends Table[(Int, Int)]("a_to_b") {
def aId = column[Int]("a")
def bId = column[Int]("b")
def * = aId ~ bId
def aFK = foreignKey("a_fk", aId, A)(a => a.id)
def bFK = foreignKey("b_fk", bId, B)(b => b.id)
}
object AToC extends Table[(Int, Int)]("a_to_c") {
def aId = column[Int]("a")
def cId = column[Int]("c")
def * = aId ~ cId
def aFK = foreignKey("a_fk", aId, A)(a => a.id)
def cFK = foreignKey("c_fk", cId, C)(c => c.id)
}
}
Now when I want to fetch all A's by id, I would also want to fetch it associations in B and C, I would do something like:
for {
a <- A if a.id >= 2
aToB <- AToB if aToB.aId === a.id
b <- B if b.id === aToB.bId
} yield (a.s, b.s)
How can I include the join to the C table? Is having something like this correct?
for {
a <- A if a.id >= 2
aToB <- AToB if aToB.aId === a.id
aToC <- AToC if aToC.aId === a.id
b <- B if b.id === aToB.bId
c <- C if c.id === aToC.cId
} yield (a.s, b.s)
Wouldn't this try to do a sub-select on aToC for each aToB as this is just a flatMap operation?
how is it possible to left outer join 2 tables?
class Person {
String firstName
String lastName
String gender
//static hasMany = [votes: Vote]
static mapping = {
version false
}
static constrains = {
}
}
class Vote {
Person voter;
Person subject;
static mapping = {
version false
}
static constraints = {
voter nullable: false
subject nullable: false
}
}
i need to get every person thats not subjected to a vote, for a specific person.
lets say person 1 votes for 3 out of 5 persons, i need the other 2 that he didnt vote for to show up for him.
How is the query supposed to be?
EDIT:
def personInstance1 = new Person(firstName: "Antonio", lastName: "Vivaldi", gender: "m")
def personInstance2 = new Person(firstName: "Dennis", lastName: "Rodman", gender: "m")
def personInstance3 = new Person(firstName: "Marc", lastName: "Oh", gender: "m")
def personInstance4 = new Person(firstName: "Gudrun", lastName: "Graublume", gender: "w")
def personInstance5 = new Person(firstName: "Hilde", lastName: "Feuerhorn", gender: "w")
def personInstance6 = new Person(firstName: "Mandy", lastName: "Muller", gender: "w")
personInstance1.save()
personInstance2.save()
personInstance3.save()
personInstance4.save()
personInstance5.save()
personInstance6.save()
def voteInstance1 = new Vote(voter: personInstance1, subject: personInstance2)
def voteInstance2 = new Vote(voter: personInstance1, subject: personInstance3)
def voteInstance3 = new Vote(voter: personInstance1, subject: personInstance4)
def voteInstance4 = new Vote(voter: personInstance1, subject: personInstance5)
def voteInstance5 = new Vote(voter: personInstance2, subject: personInstance1)
voteInstance1.save()
voteInstance2.save()
voteInstance3.save()
voteInstance4.save()
voteInstance5.save()
this is my grails bootstrap-file , Antonio and Dennis have voted, and each need to be presented a list of people they didnt vote for.
EDIT:
this way i seem to get a result for Dennis, since he only voted once,
but if i put v.voter_id = 1,
to get a result for Antonio, the result doubles according to how many votes he did.
SELECT first_name FROM vote as v
LEFT OUTER JOIN person as p
ON v.subject_id != p.id AND v.voter_id = 2
WHERE p.id IS NOT NULL
Try this:
SELECT * FROM Person P
WHERE NOT EXISTS(
SELECT 'Vote' FROM Vote V
WHERE V.subject = P
)
In this way you'll extract all Person without Vote
EDIT
In SQL you can retrieve a matrix in this way:
CREATE TABLE #person (nome varchar(30))
CREATE TABLE #vote (votante varchar(30), candidato varchar(30))
INSERT INTO #person values
('Antonio Vivaldi'),
('Dennis Rodman'),
('Marc Oh'),
('Gudrun Graublume'),
('Hilde Feuerhorn'),
('Mandy Muller')
INSERT INTO #vote values
('Antonio Vivaldi', 'Dennis Rodman'),
('Antonio Vivaldi', 'Marc Oh'),
('Antonio Vivaldi', 'Gudrun Graublume'),
('Antonio Vivaldi', 'Hilde Feuerhorn'),
('Dennis Rodman', 'Antonio Vivaldi')
SELECT *
FROM #person p
CROSS JOIN #person c
WHERE NOT EXISTS(
SELECT 'X'
FROM #vote v
WHERE v.votante = p.nome
AND v.candidato = c.nome
)
AND p.nome <> c.nome
ORDER BY p.nome
Is there a way to automatically wrap all searches with a wildcard?
e.g.:
Book.search("*${params.q}*", params)
I'm not familiar with .search (are you using a plugin?). However, for a wildcard search in models, I typically create a method inside the domain model class. In your example,
In the Book model class:
class Book {
String title
String author
int year
static List wildSearch(par, val) {
def foundList = this.executeQuery("select b FROM Book b WHERE ${par} like \'%${val}%\'")
return foundList
}
}
In your controller:
def searchBook = {
def b1 = new Book(title: "Farewell To Arms", author: "Ernest Hemingway").save()
def b2 = new Book(title: "The Brother's Karamazov", author: "Anton Chekov").save()
def b3 = new Book(title: "Brothers in Arms", author: "Cherry Dalton").save()
// If you search for "Arms", This returns b1 and b3
def found = Book.wildSearch("title", params.title)
}
Example URL:
http://localhost:8080/mytest/mycontroller/searchBooks?title=Arms
Class Buyer {
String name
static constraints = {
}
}
Class Order {
String ref
static belongsTo = [buyer:Buyer]
static constraints = {
buyer(nullable:false)
}
}
In OrderController.groovy
...
def someAction = {
//working
def data1 = ["buyer.id": 2, "ref": "xyz"]
def ord = new Order(data1);
ord.save();
def data2 = ["buyer.id": 2, "ref": "234xyz"]
def ord2 = new Order(data2);
ord2.save();
//But in a loop - its not working
def items = ['abc', 'def', 'ghi', 'jkl']
def data2 = [:]
for(e in items) {
data2 = ["buyer.id": 2, "ref" : e.value] //keeping buyer id same
def ord = new Order(data2);
ord.save();
data2 = [:] //just emptying it?
}
}
As you would notice in "working" above, if I am able to save multiple rows by copy pasting and definging new maps but If I try to loop through an array, it doesnt work. Any ideas how do I save data by looping through an array or a map?
Any questions, please let know
Thanks
First, I'm not sure about ["buyer.id": 2, "ref" : e.value], I think it should be [buyer: Buyer.get(2), ref : e.value].
Second, I would recommend using cascading save to do the task. You can try something like this(You need to define a static hasMany = [orders: Order] relation in Buyer for Buyer-Order relationship.
Buyer b = new Buyer(name: "foo")
for(e in items) {
def ord = new Order(ref: e.value);
b.addToOrders(ord)
}
b.save(flush:true)
You should just be able to do:
def someAction = {
def items = ['abc', 'def', 'ghi', 'jkl']
items.each { item ->
def ord = new Order( [ 'buyer.id':2, ref:item ] )
ord.save()
}
}
What errors (if any) are you getting?
Also, why are you doing e.value? This will get you an array of Character rather than a String (which is what your first working example is using)
Below is my code.
Here I am getting an error which is 'No such property: it for class: emp.EmployeeController'.
I think I am doing something wrong here.
Any advice??
def list ={
def id=params.id
def results
String employee="SELECT empName, empDate, empNo from employee where empId='id'"
String referrer="SELECT empName, empDate, empNo from referer where empId='id'"
def employeeInstanceList = new ArrayList<Employee>()
Sql sql = new Sql(dataSource)
def joining=null
joining = sql.rows( "select joining from employee_dates")
if (joining!=null)
results = sql.eachRow(employee)
employeeInstanceList=getCalculatedEmployeeData(results)
/*{
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee
}*/
else
results = sql.rows (currentDaySql)
employeeInstanceList=getCalculatedEmployeeData(results)
/*{
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee }*/
}
[employeeInstanceList: [employeeInstanceList: employeeInstanceTotal: Employee.count()]
}
def getCalculatedImpactData(def results){
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee }*/
return [employeeInstanceList: employeeInstanceList]
}
Thanks,
Meghana
i would second leebutts answer... but just a pointer, the usage of the it keyword is usually confined to closures... so instead of doing this in java:
List l = [];
for (Iterator i = l.iterator(); i.hasNext(); ) {
...do something adressing List l at position i...
}
you could do this in groovy / grails:
list.each { it ->
...do something with each object in the list (it)...
}
but you should really read up on groovy closures at http://groovy.codehaus.org/Closures
There is so much wrong with that code, I don't know where to start...
But to avoid getting more down votes I have tried :)
I tried to copy your code into an IDE and try and work out what you are trying to achieve but couldn't.
This is as close as I could get it:
def list = {
def id = parmas.id
def results
String employee = "SELECT empName, empDate, empNo from employe"
def employeeInstanceList
Sql sql = new Sql(dataSource)
def joining = sql.rows("select joining from employee_dates")
if (joining != null) {
results = sql.eachRow(employee)
employeeInstanceList = getCalculatedEmployeeData(results)
}
else {
results = sql.rows(currentDaySql)
employeeInstanceList = getCalculatedEmployeeData(results)
}
[employeeInstanceList: employeeInstanceList, employeeInstanceTotal: Employee.count()]
}
def getCalculatedImpactData(def results) {
def employeeInstanceList = new ArrayList<Employee>()
results.each { it ->
def employee = new Employee()
employee.empName = it.empName
employee.empNo = it.empNo
employee.empDate = it.EmpDate
employeeInstanceList.add(employee)
}
return employeeInstanceList
}
but it is still referring to a variable currentDaySql which doesn't exist and I'm not sure what you're trying to do with the 'joining' result.
You really need to read up on Groovy basics.
The block of code where the error occurs is probably:
def getCalculatedImpactData(def results){
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee
return [employeeInstanceList: employeeInstanceList]
}
it is not defined anywhere (hint: the compilation error told you this). Like Sebastian said, it is typically used in closures; what you've defined here is a function. Presumably you wanted to use results (or something) instead of it here.
I'm assuming that some of the things in your code (e.g. comment opening/closing) weren't in there and were added between when you saw the error and when you posted the code. Otherwise you'd get other errors.