Quantcast

Grails domain class with ArrayList property

classic Classic list List threaded Threaded
3 messages Options
pgf
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Grails domain class with ArrayList property

pgf
I am having trouble with a domain class that has a property defined as ArrayList. I am able to update the property and save the object, but the property resets to null. Here is the domain:

package org.example

import java.util.List;

class Book {
    String title
    String isbn
	ArrayList myList
	int counter
	
	static hasMany = [ authors: Author]
	static belongsTo = Author
	
    static constraints = {
        title(blank: false)
        authors(nullable: true)
    }
}

I am updating it in a service, which is called by a controller. The service is:

package org.example

class TestService {

	ArrayList myList
	
    def serviceMethod() {
		
		def counter
		def book = Book.get(2)
		myList = book.getMyList()
		println "In service 1: " + book.getMyList() + " counter: " + book.getCounter()
		
		if (myList == null) {
			println "Initializing myList"
			myList = new ArrayList()
		}
		
		counter = book.getCounter() ? book.getCounter() : 0
		
		myList.add(counter++)
		myList.add(counter++)
		
		book.setMyList(myList)
		book.setCounter(counter)
		book.save(failOnError: true, flush: true)
		println "In service 2: " + book.getMyList()

    }
}

I call the service method in the list() method of the Book controller and I print out the values of the list and counter in the service and also in the controller. I see counter incrementing each time - good. In the controller, right after calling the service, I see the ArrayList has two entries and they are consistent with the value of counter. When I refresh the page (i.e. call the list() method again) I see that the ArrayList is null, although counter is now 2:

Output on first invocation:
In service 1: null counter: 0
Initializing myList
In service 2: [0, 1]
In controller: [0, 1]

Output on refreshing page:
In service 1: null counter: 2
Initializing myList
In service 2: [2, 3]
In controller: [2, 3]

Questions:
1. why is the counter being saved but the ArrayList is not?
2. if the ArrayList is not saved across page refreshes, why is it saved long enough to see it in the controller?

Regards,

Peter Farr
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Grails domain class with ArrayList property

andy_mccullough
This post has NOT been accepted by the mailing list yet.
was there ever a solution to this?
pgf
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate
star

Re: Grails domain class with ArrayList property

pgf
No solution - had to redesign the code.

Regards,

Peter Farr
Loading...