Mikey
Mikey

Reputation: 4742

Grails: hasMany isn't working... I think I'm doing something wrong with my hibernate session

I have a fresh grails 1.3.7 with two domain classes with some tricky relationships:

class NodePoint {
  String name
  static mappedBy=[outgoingConnections:'startPoint',incomingConnections:'endPoint']
  static hasMany=[outgoingConnections:Connections, incomingConnections:Connections]
}

class Connections {
  NodePoint startPoint
  NodePoint endPoint

}

I am doing something wrong in the bootstrap (project is "todaysstupidproblem"):

import todaysstupidproblem.*
class BootStrap {

  def init = { servletContext ->
    def startingPoint = new NodePoint(name:"This Point").save(failOnError:true)
    def endingPoint = new NodePoint(name:"That Point").save(failOnError:true)
    def someConnex = new Connections(startPoint:startingPoint,endPoint:endingPoint).save(failOnError:true, flush:true)
    println someConnex
    println "WHY ISNT THERE SOMETHING BETWEEN THESE???"
    startingPoint.outgoingConnections.each{
      println "WHY AM I NOT SEEING THIS!!?!?!?!?"
      println "Where did the outgoingConnections go?"
      println it
    }
    println "HIBERNATE FTL :("
  }
  def destroy = {
  }
}

Is printing:

Running Grails application..
todaysstupidproblem.Connections : 1
WHY ISNT THERE SOMETHING BETWEEN THESE???
HIBERNATE FTL :(
Server running. Browse to http://localhost:8080/todaysstupidproblem

Why isn't the connection printing?

Upvotes: 0

Views: 317

Answers (2)

Mikey
Mikey

Reputation: 4742

Oh yeah it was the session. I added in this line:

NodePoint.withSession { it.clear() }

And then reload the startPoint with NodePoint.list().find{it} and it's there!

Special thanks to @BurtBeckwith for having this solution hidden in a comment to another one of my questions!

Upvotes: 0

aldrin
aldrin

Reputation: 4572

That's because the startingPoint.outgoingconnections is null and not initialized to anything. While someConnex has references to startingPoint and endingPoint, the back references have not been initialized. Try adding this before the each loop,

startingPoint.addToOutgoingConnections someConnex

Upvotes: 1

Related Questions