views:

135

answers:

1

Hello Everyone,

I started using groovy intensely to prototype everything. This is amazing.
But I faced the problem with groovy shell.
Next code I run with

groovy filename.groovy

and everything works as expected.
But within groovysh command

load filename.groovy

Doesn't work: it can't find class Book.

The code:

import org.hibernate.cfg.*
import org.hibernate.ejb.*
import javax.persistence.*

@Entity class Book {
    @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long id
    public String author
    public String title
    String toString() { "$title by $author" }
}

hibernateProperties = [
    "hibernate.dialect": "org.hibernate.dialect.HSQLDialect",
    "hibernate.connection.driver_class": "org.hsqldb.jdbcDriver",
    "hibernate.connection.url": "jdbc:hsqldb:mem:demodb",
    "hibernate.connection.username": "sa",
    "hibernate.connection.password": "",
    "hibernate.connection.pool_size": "1",
    "hibernate.connection.autocommit": "true",
    "hibernate.cache.provider_class": "org.hibernate.cache.NoCacheProvider",
    "hibernate.hbm2ddl.auto": "create-drop",
    "hibernate.show_sql": "true",
    "hibernate.transaction.factory_class": "org.hibernate.transaction.JDBCTransactionFactory",
    "hibernate.current_session_context_class": "thread"
]

properties = new Properties()
hibernateProperties.each { k, v -> properties.setProperty(k, v) }
cfg = new Ejb3Configuration()

emf = cfg.addProperties(properties).addAnnotatedClass(Book.class).buildEntityManagerFactory()
em = emf.createEntityManager()
query = em.createQuery("SELECT b FROM Book b")

println query.getResultList()

In fact if you write Book class as

@Entity 
class Book {
    @Id @GeneratedValue(strategy = GenerationType.AUTO) 
    public Long id
    public String author
    public String title
    String toString() { "$title by $author" }
}

Groovy Shell won't understand annotations when you execute

load filename.groovy

So to play with JPQL I have to move Entity to the separate file, groovyc it and then load groovy shell. Not the worst case but would be great if I can just load the prototype inside shell.

Do you have any ideas how to solve this out?

A: 

The short answer is I don't think there's a way around this. If your going to reuse the Book class with out changing it often you could always compile it once then add it to your classpath so Groovy would pick it up every time you use the shell.

Jared
I know the workaround. I want to figure out the difference between groovysh loaded class and groovy loaded class
Mykola Golubyev