Hibernate + Dynamic Groovy Class (Is this even possible)

classic Classic list List threaded Threaded
9 messages Options
Reply | Threaded
Open this post in threaded view
|

Hibernate + Dynamic Groovy Class (Is this even possible)

caden.whitaker@gmail.com
Hey all, this is a direct copy of a question I posted on Java Ranch, but I'm getting no feedback, any help would be appreciated. The original question can be found here ( http://www.coderanch.com/t/513878/ORM/java/Hibernate-Dynamic-Groovy-Class-even )

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);

Fairly straight forward right?
In a nutshell, the JSP is compiling the groovy file and then invoking the "test" method that tries to put test data through hibernate. The file compiles, but it bombs at the test call with the error Unknown entity: com.test.User

I understand the error, do you get what I'm trying to do? Basically I'm trying to dynamically load a class into hibernate and have it create the tables and the content. Is this even possible? Any help would be really appreciated.




Reply | Threaded
Open this post in threaded view
|

Re: Hibernate + Dynamic Groovy Class (Is this even possible)

Andre Steingress
you need to get a reference to the application's sessionfactory, modify the configuration and refresh the session factory.

although it sounds pretty straight forward in theory it is hard to get it right in practice - you need to ensure that refreshing works across multiple threads, you need to consider currently running sessions etc etc

If you are using Spring there is an unresolved issue for LocalSessionFactoryBean for exactly that use-case: https://jira.springframework.org/browse/SPR-4308

Andre

Am 17.10.2010 um 01:56 schrieb caden whitaker <[hidden email]>:

Hey all, this is a direct copy of a question I posted on Java Ranch, but I'm getting no feedback, any help would be appreciated. The original question can be found here ( http://www.coderanch.com/t/513878/ORM/java/Hibernate-Dynamic-Groovy-Class-even )

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);

Fairly straight forward right?
In a nutshell, the JSP is compiling the groovy file and then invoking the "test" method that tries to put test data through hibernate. The file compiles, but it bombs at the test call with the error Unknown entity: com.test.User

I understand the error, do you get what I'm trying to do? Basically I'm trying to dynamically load a class into hibernate and have it create the tables and the content. Is this even possible? Any help would be really appreciated.




Reply | Threaded
Open this post in threaded view
|

Re: Hibernate + Dynamic Groovy Class (Is this even possible)

caden.whitaker@gmail.com
Woah thanks for the reply. Basically I just want my groovy code to have SOME sort of orm, but still have the benefits of being dynamic groovy-compiled-on-the-fly. Hibernate is what I am most used to, but how you describe it makes it look like hibernate generally does not support this, which means a core component of my architecture will be a "hack". That leaves a bad taste in my mouth. Do you know of a better way to handle what I am trying to do (implement ORM like functionality in dynamic groovy) maybe using some native groovy options or a different orm?
Reply | Threaded
Open this post in threaded view
|

Re: Hibernate + Dynamic Groovy Class (Is this even possible)

John Hartnup
I'm guessing the answer will be GORM, the ORM component used in Grails.

On 18 October 2010 14:20, [hidden email] <[hidden email]> wrote:

Woah thanks for the reply. Basically I just want my groovy code to have SOME
sort of orm, but still have the benefits of being dynamic
groovy-compiled-on-the-fly. Hibernate is what I am most used to, but how you
describe it makes it look like hibernate generally does not support this,
which means a core component of my architecture will be a "hack". That
leaves a bad taste in my mouth. Do you know of a better way to handle what I
am trying to do (implement ORM like functionality in dynamic groovy) maybe
using some native groovy options or a different orm?
--
View this message in context: http://groovy.329449.n5.nabble.com/Hibernate-Dynamic-Groovy-Class-Is-this-even-possible-tp3215787p3217387.html
Sent from the groovy - user mailing list archive at Nabble.com.

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

   http://xircles.codehaus.org/manage_email





--
"There is no way to peace; peace is the way"
Reply | Threaded
Open this post in threaded view
|

Re: Hibernate + Dynamic Groovy Class (Is this even possible)

caden.whitaker@gmail.com
I was looking at GORM but it appears to be using Hibernate 3 as the underlying engine, before I blow another few days do you know or have direct experience with dynamically compiling groovy to work with GORM?
Reply | Threaded
Open this post in threaded view
|

Re: Hibernate + Dynamic Groovy Class (Is this even possible)

Andre Steingress
In reply to this post by caden.whitaker@gmail.com
I don't know your requirements but I would reconsider if you really need to create and compile Hibernate entity classes at runtime. A much simpler approach would be to create the Hibernate entities in advance, but based on an abstract meta-model instead of mapping a dynamically created entity one-to-one to a database table.

Another option would be to take a look at Redis/GORM for Redis

http://code.google.com/p/redis/
http://blog.springsource.com/2010/09/07/announcing-gorm-for-redis/

Since Redis is a key-value DB, persisting dynamic entities should not be a big deal.

For further information on GORM for Redis or GORM in general you should ask on the Grails mailing list.

Andre

caden.whitaker@gmail.com wrote
Woah thanks for the reply. Basically I just want my groovy code to have SOME sort of orm, but still have the benefits of being dynamic groovy-compiled-on-the-fly. Hibernate is what I am most used to, but how you describe it makes it look like hibernate generally does not support this, which means a core component of my architecture will be a "hack". That leaves a bad taste in my mouth. Do you know of a better way to handle what I am trying to do (implement ORM like functionality in dynamic groovy) maybe using some native groovy options or a different orm?
Reply | Threaded
Open this post in threaded view
|

Re: Hibernate + Dynamic Groovy Class (Is this even possible)

David Clark
In reply to this post by caden.whitaker@gmail.com
I think GORM is your best option because it takes care of the dynamic dispatch internally.  However, I don't know if GORM can dynamically create properties.  I know it will dynamically create methods for issuing queries, but if they have dynamic properties working that's a real nice trick!

The issue with hibernate is that it views the world in terms of statically defined entities.  It uses this information to be much more efficient.  By knowing the structure of entities ahead of time it can do many tricks which dynamically generated properties are going to kill (or at least make a lot harder), such as lazy loading and query caching.  Lazy loading expensive properties (such as binary BLOBS) and collections is a huge performance gain.  Query caching is also nice because hiberate does not have to figure out just which query it should run, it can cache queries internally.  There are others as well.  By resolving all of these things at load time hibernate can be much more effiecient.

My project takes a middle ground.  I have a step in my build script which regenerates all entities based on the database schema.  I wrote this when the project was pure java (about 6 years ago).  It's now a mixed groovy/java project, but the entities are all in groovy.  I just modified the regeneration step to emit groovy instead of java.  This gives me all of the benefits of static definition for hibernate, but it does give a lot of the advantages of dynamic code generation.  I have never written an entity or xml mapping file by hand and my entities are always in synch with my database schema.


On Monday, October 18, 2010, you wrote:
>
> I was looking at GORM but it appears to be using Hibernate 3 as the
> underlying engine, before I blow another few days do you know or have direct
> experience with dynamically compiling groovy to work with GORM?
>


--
David

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


Reply | Threaded
Open this post in threaded view
|

Re: Hibernate + Dynamic Groovy Class (Is this even possible)

caden.whitaker@gmail.com
Gotcha, and thanks all for the replies. Ideally I'd be running a system where I would have a bean that would compile all of the groovy classes at application startup and then invoke hibernate after that. Adding new classes would involve recompiling everything again and restarting hibernate (Again). I'm not too worried about existing users/instances/sessions/threads as this would be a build situation where anyone using the system would be forcibly evicted. At first it sounded like a pretty easy job, but it looks like there is going to be more to it than I expected. I'll start investigating Gorm on the Grails mailing list. Thanks again!
Reply | Threaded
Open this post in threaded view
|

Re: Hibernate + Dynamic Groovy Class (Is this even possible)

Jochen Theodorou
[hidden email] wrote:
> Gotcha, and thanks all for the replies. Ideally I'd be running a system where
> I would have a bean that would compile all of the groovy classes at
> application startup and then invoke hibernate after that. Adding new classes
> would involve recompiling everything again and restarting hibernate (Again).
> I'm not too worried about existing users/instances/sessions/threads as this
> would be a build situation where anyone using the system would be forcibly
> evicted. At first it sounded like a pretty easy job, but it looks like there
> is going to be more to it than I expected. I'll start investigating Gorm on
> the Grails mailing list. Thanks again!

have you considered using something like db4o?

bye blackdrag

--
Jochen "blackdrag" Theodorou
The Groovy Project Tech Lead (http://groovy.codehaus.org)
http://blackdragsview.blogspot.com/


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email