GORM + Dynamic Groovy Class (Is this even possible)

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

GORM + Dynamic Groovy Class (Is this even possible)

caden.whitaker@gmail.com
    Hey all, 

So I've been posting, searching, and trying to find some information to a fairly general query. Here are some of the references

First time asked:
http://www.coderanch.com/t/513878/ORM/java/Hibernate-Dynamic-Groovy-Class-even 

Second time asked:
http://groovy.329449.n5.nabble.com/Hibernate-Dynamic-Groovy-Class-Is-this-even-possible-td3215787.html

I'm going to repost my code here at the bottom, But here is the core question: I'm investigating the concept of Groovy classes as uncompiled files that are compiled on startup. I'd like these classes to have the benefits of an ORM. Is this possible? How can I go about doing this? I'd prefer to not have this be tied to a specific web architecture just yet. Can  I do this with GORM? Any help would be appreciated. Here is my code example:

I've got a file on my machine called User.groovy
package com.test;

 
package com.test;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import com.test.DataUtils;

@Entity
@Table(name = "user")
public class User {

    public test() {
        def manager = DataUtils.getInstance().createEntityManager()
        manager.getTransaction().begin()
        manager.persist new User(name: "Peter")
        manager.getTransaction().commit()
    }
   
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", nullable = false)
    Long id;

    @Basic
    @Column(name = "Name", nullable = true, unique = false)
    String name;
}


Then I created a JSP to read in that file and compile it dynamically:

        File file = new File("C:\\User.groovy");
        StringBuffer contents = new StringBuffer();
        BufferedReader reader = null;

        reader = new BufferedReader(new FileReader(file));
        String text = null;

        // repeat until all lines is read
        while ((text = reader.readLine()) != null)
        {
            contents.append(text)
                .append(System.getProperty(
                    "line.separator"));
        }

        // show file contents here
        System.out.println(contents.toString());

        GroovyClassLoader gcl = new GroovyClassLoader();
        Object[] args = {};
       ((GroovyObject)gcl.parseClass(contents.toString()).newInstance()).invokeMethod("test", args);