Reuse your Hibernate/JPA domain model with Grails |
|
It's a common story. You have an existing database and now you want to add a web application for it with the minimum of fuss. Is Grails up to the task? Of course it is! Even better, if you already have a domain model based on JPA or Hibernate configuration files, you can reuse it and still benefit from the great GORM features you're used to.
The first step in reusing an existing domain model is to get the class files on the application's classpath. You can do this either by packaging them up in a JAR file and including it in the application (typically by dropping it in the 'lib' directory), or by putting the source files in the 'src/java' directory. The JAR file is the better approach when sharing a model between applications, but you then need a multi-project build system to ensure that the JAR is always up to date for all projects. It's probably worth the extra effort and both Gradle and Maven have plugins for building Grails projects. Alternatively, if your Grails application is the only project using the model going forward, you should keep the source in 'src/java' instead.
Once you've decided on how to incorporate the domain model, you need to tell Grails about it. How you do that depends on whether you're using Hibernate configuration files or JPA annotations.
XML configuration files
Hibernate XML mapping files are old school, but they have the advantage of keeping all the mapping information in one place. To use them from your Grails application, simply create the file grails-app/conf/hibernate/hibernate.cfg.xml with the content:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping resource="org.example.Book.hbm.xml"/>
<mapping resource="org.example.Author.hbm.xml"/>
...
</session-factory>
</hibernate-configuration>
Make sure you add a <mapping> element for each of your Hibernate mapping files and drop those mapping files into grails-app/conf/hibernate. Amazingly, that's all you have to do! So what about annotated models?
JPA annotations
As with the Hibernate mapping files, you have to create the grails-app/conf/hibernate/hibernate.cfg.xml file. This time, you've got a bit more work to do as you have to add a <mapping> entry for every domain class:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="org.example.Book"/>
<mapping class="org.example.Author"/>
...
</session-factory>
</hibernate-configuration>
Not much fun I grant you, but at least you only have to do it once.
If you're using Grails 1.1.x or earlier, there's one more task to undertake: you have to tell Grails that this is an annotation-based model by adding the following to grails-app/conf/DataSource.groovy:
dataSource {
configClass = "org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration"
...
}
You don't have to do this for Grails 1.2+ because GrailsAnnotationConfiguration is the default setting in those versions. Next time you run your Grails application, you'll have access to all your annotated domain classes.
Note Since version 1.3.2, you have been able to use the Grails command create-hibernate-cfg-xml to generate the Hibernate configuration file for you. Saves typing/copy-pasting!
One glaring gap remains in the domain model from a GORM standpoint: constraints. You can't define them in your Java classes, but without them, GORM validation is useless. Fortunately, you can attach constraint metadata to a class by adding a package.DomainClassConstraints.groovy script to 'src/java'. For example, if you have a domain class org.example.LibraryBook, then you should add the file src/java/org/example/LibraryBookConstraints.groovy. Inside this script you define your constraints block like so:
constraints = {
name(blank: false)
age(min: 0, max: 120)
...
}
You may be wondering why the script goes in the 'src/java' directory. That's a good question. Grails requires the constraints script in source form, so you need to put it in a location which results in Grails including the .groovy file (not the compiled class) in the WAR. The 'src/java' directory is the only location that satisfies this requirement.
It really is surprisingly simple to incorporate a Java domain model in your Grails applications. You may lose the elegance and custom mappings of standard GORM domain classes, but you are still able to use dynamic finders, criteria queries, validation, etc. What about scaffolding? Grails will do its best to scaffold your domain model, but it makes no guarantees. As long as the model is straightforward, the scaffolding should work fine. Reusing a domain model is also a great way of trying out Grails since you don't have to create one from scratch.
Note that if you simply want to access a legacy database and don't have an existing domain model, then you are almost certainly better off using standard GORM domain classes with custom mappings. Both approaches are documented in the user guide: Hibernate mappings and the custom mapping DSL.
One final thing: if you've used a Java domain model in your own Grails project, I'd be interested to hear about your experiences. Anything that can help other users who want go down this path would be much appreciated!
Similar Posts
- Grails 1.1 Released
- First Grails Release Under the SpringSource Banner
- Announcing GORM for Redis
- GORM Gotchas (Part 1)
- Grails 1.1.1 released with Google AppEngine support





Thomas Einwaller says:
Added on August 26th, 2010 at 3:07 pmI wish this article was written four months ago, would have saved me some troubles
but I can confirm that this works great!
Rick says:
Added on August 27th, 2010 at 2:01 pmI've got several apps that use the same Hibernate domain classes and mappings so they're in a jar file.
I've used them in a Grails app by copying my existing hibernate.cfg.xml into grails-app/conf/hibernate. Hibernate seems to find the mapping files in the jar with no trouble.
Dan says:
Added on August 29th, 2010 at 12:24 pmIf I write an application from scratch, is there anyway to export the hibernate mapping file out?
Peter Ledbrook (blog author) says:
Added on August 31st, 2010 at 4:51 am@Dan I don't think so. There is a grails schema-export command, but that outputs SQL. Generating Hibernate mapping files from a GORM model hasn't been requested before. Do you have a particular use case in mind?
Chris says:
Added on September 14th, 2010 at 9:19 pmDoes Grails (GORM and/or scaffolding) support @MappedSuperclass JPA annotations on imported Java domain classes?
For example, I am working with a @MappedSuperclass abstract class PersistentEntity that has the @Id and typical auditable fields defined. This is then extended by all of the Java domain classes. [That's a simple case, but there are other more complex mapped superclasses throughout this particular domain model.]
So far I have not been able to get this to work in Grails. Should I include PersistentEntity as a mapping class in the grails hibernate.cfg.xml or not? Does it matter that it is in a different package than my other Java domain classes? Can Grails parse my PersistentEntityConstraints.groovy file for constraints about the fields in the mapped superclass?
I have searched around through the Grails docs, stack overflow, infoq tutorial, etc. The only thing I've found is that for regular (pure Groovy) GORM domain classes, if you mark a class as abstract, then GORM will not try to create a table for it (but it also looks like it will not honor mapping changes for non-default column names, etc).
Any pointers would be much appreciated!
Peter Ledbrook (blog author) says:
Added on September 23rd, 2010 at 10:52 am@Chris Sorry, I've been on holiday recently. I can't answer your question but I'll see if I can get someone to take a look.
Thomas Einwaller says:
Added on October 17th, 2010 at 4:49 pmI just found out that my Hibernate configuration uses the DefaultNamingStrategy per default and the Grails app with the same domain model uses the ImprovedNamingStrategy – this could lead to problems! I wrote a blog post about it:
http://dertompson.com/2010/10/17/be-careful-when-reusing-hibernate-domain-model-in-grails/
Tarun Arora says:
Added on November 7th, 2010 at 3:32 pmHow can we use named queries declared in mapping files? I have couple of them and i'm finding difficulty in executing them the same way as specified in GRAIL documentation.
http://grails.org/doc/latest/ref/Domain Classes/namedQueries.html
Thanks
Peter Ledbrook (blog author) says:
Added on November 11th, 2010 at 5:50 am@Chris Sorry, I was never able to find an answer for you.
@Tarun Grails named queries are not the same as Hibernate named queries, hence why you can't call them. I don't have any experience with Hibernate named queries, but it looks like you should be able to access them through the session:
MyDomainClass.withSession { session -> def q = session.getNamedQuery("all.available") q.list() }'Tarun Arora says:
Added on November 11th, 2010 at 9:44 amThanks Peter.
I did find that out. I should have posted earlier. I went the same route as you have mentioned.
Jeremy Flowers says:
Added on November 30th, 2010 at 5:28 amHey Peter, do the constraints need to be declared as static?
Peter Ledbrook (blog author) says:
Added on November 30th, 2010 at 5:33 am@Jeremy I believe that 'constraints' is a script variable, so it shouldn't be declared with either static or def. Nor should it be inside a class definition.
Jeremy Flowers says:
Added on November 30th, 2010 at 6:31 amAt what point in the build life cycle do the groovy constraints get picked up? For example will grails run-app just magically take care of the java class decoration of the constraints?
Jeremy Flowers says:
Added on November 30th, 2010 at 6:50 amAlso do you need package name in your constraints script?
Peter Ledbrook (blog author) says:
Added on November 30th, 2010 at 7:25 amThe constraints are picked up during GORM initialisation. Also, the constraints script should not include a package statement.
Vijay says:
Added on February 27th, 2011 at 8:39 pmI had hibernate mapping files and wrote the domain classes in groovy. I had to place them in src/groovy and not in the domain directory because otherwise I got "Duplicate entity.." exception.
With scaffolding enabled in the controller, when I access the web pages, the List works fine but the Create page does not show my Id field – even if the generator is 'assigned'.
The Edit page cannot be displayed – shows error "No such property: version".
So, can scaffolding be used in such cases?
Peter Ledbrook (blog author) says:
Added on February 28th, 2011 at 5:20 amThe scaffolding templates do make assumptions about the model. I'm not familiar with what those assumptions are, but you can probably easily resolve the problem by installing the scaffolding templates with the
grails install-templatescommand and modifying them to suit your domain model. It depends what the current errors are.The reference to 'version' is because the scaffolding manually deals with optimistic locking, which requires the 'version' property on domain classes. If you disable the version field, then you will have to remove the optimistic locking code from the scaffolding templates.
Vijay says:
Added on March 4th, 2011 at 4:03 pmWhat about Java domain objects mapped using hibernate? I tried that too. These objects are accessible and fine if I use them using the session (from injected sessionFactory)but the scaffolding does not work on these.
I get the following error/exception if I set scaffolding to my Java class.
2011-03-04 15:57:26,077 [http-8080-1] ERROR view.ScaffoldingViewResolver – Erro
r generating scaffolded view [/sample/list]: null
java.lang.NullPointerException
at java.lang.Class.isAssignableFrom(Native Method)
at java_lang_Class$isAssignableFrom.call(Unknown Source)
at SimpleTemplateScript2$_run_closure1.doCall(SimpleTemplateScript2.groo
vy:29)
at SimpleTemplateScript2.run(SimpleTemplateScript2.groovy:29)
at java.lang.Thread.run(Thread.java:619)
Peter Ledbrook (blog author) says:
Added on March 9th, 2011 at 9:13 amAgain, this is probably down to the specific model. In this case, the scaffolding doesn't like at least one of the properties on your domain class. If you install the templates and have a look at 'src/templates/scaffolding/list.gsp', you'll see that the isAssignableFrom() call is on line 26. You could try removing that or perhaps better add a null-check.
Strayph says:
Added on March 27th, 2011 at 10:40 pmHello, Peter,
Amazing article, and great response to all the feedback.
I have an Eclipse project with our existing Hibernate domain models. I created a new Grails Project in Eclipse, and then added my domain project under Preferences/Java Build Path/Projects.
I generated the hibernate.cfg.xml file, and added both and
entries.
Unfortunately, when I try to 'grails run-app', I get a (deeply nested) exception:
nested exception is org.hibernate.MappingException: Unable to load class declared as in the configuration:
Apparently, my grails project hibernate configuration cannot find the class. Any thoughts on what else I could do?
Strayph says:
Added on March 27th, 2011 at 10:51 pmWhoops….I put angle brackets in my last post. I meant to say I had added "mapping package" and "mapping class" annotations in the hibernate.cfg.xml file.
Strayph says:
Added on March 27th, 2011 at 10:52 pmAlso, the error was:
Unable to load class declared as <mapping class="com.MyPackage.MyClass"/> in the configuration:
… 23 more
Peter Ledbrook (blog author) says:
Added on March 28th, 2011 at 9:29 amStrayph: are your domain classes in a JAR file in the 'lib' directory or under src/java? If neither, then Grails will not be able to find the classes.
Strayph says:
Added on March 28th, 2011 at 12:47 pmHi, Peter,
I have tried connecting the project via Eclipse Java Build Path, and I have tried explicitly copying the JAR file into the grails project's lib directory, but always get the "Unable to load class" error. (I am trying to avoid recopying the .java files over from the original project.)
Thanks for the quick response. I am on IRC at freenode#grails channel if you'd like to chat, otherwise I'll take whatever help I can get.
Jerry says:
Added on May 21st, 2011 at 10:26 amHi Stryph
I am getting the same problem. I have added my jar file in the lib directory, but keep getting ClassNotFoundException for some of the mapped classes. I am certain these classes are there in the jar file, but for some strage reason keep getting the exception.
It does seem to load some of the classes though.
Would appreciate any help with this.
regards,
Jerry
Jerry says:
Added on May 21st, 2011 at 1:49 pmFigured out my problem. I am migrating a struts app to Grails and reusing the JPA entities. The entities were implementing Acegi interfaces, which caused the exception.
But it is really strange that this results in ClassNotFoundException. It is very misleading.
Peter Ledbrook (blog author) says:
Added on May 23rd, 2011 at 8:25 amUnfortunately ClassNotFoundExceptions can often report the incorrect class. For example, the reported class may be on the classpath but one of its dependencies might not. I think this may be a Java issue rather than a Groovy/Grails one. Either way, I don't know how to fix the problem (if it's even possible). Sorry.
Joseph says:
Added on May 23rd, 2011 at 12:17 pmI have some JPA annotated classes from a Jar file that I use to create my domain classes,
everything works fine, connection to the DB is perfect, but the only caviat are the constraints which are ignored, I've red thru this article and added the package.DomainClassConstraints.groovy to src/java as mentioned in this article,
From here everything looks good, but when I run the app the console gets into an infinite cycle…
and keeps re-compiling without end… any pointings about this?
Running Grails application..
Configuring Spring Security …
Server running. Browse to http://localhost:8080/my-app
Running Grails application..
Configuring Spring Security …
Server running. Browse to http://localhost:8080/my-app
Peter Ledbrook (blog author) says:
Added on May 24th, 2011 at 2:59 amJoseph: I suspect that you have puy the *Constraints.groovy file in src/groovy rather than src/java. That means the Groovy compiler tries to compile it (which isn't what you want).
As a general note, when you run into this issue of constant restarting, stop the server and then run the command "grails compile –verboseCompile". This will tell you exactly which file is being recompiled and you can then work out whether the package matches the directory structure and the class name matches the filename.
Jerry says:
Added on June 1st, 2011 at 7:19 amThanks for the earlier response Peter.
I am still struggling with the configuration. I have quite a lot of modular code already written in Spring and JPA and i want to reuse the back end code and migrate only the struts 2 app to grails. I am using maven as the build tool and have added dependencies to other maven modules. I followed the maven plugin documentation for grails and the project seems setup properly. I am trying to run the mvn grails:exec -Dcommand=generate-controller and passing an existing JPA class as the -Dargs.
I end up error that says 'beanName' must not be empty. I am pretty sure i have all the correct dependencies set up, but the command refuses to run successfully.
Any hints on what might be happening? Thanks for your help.
Brief stack trace is as follows
Caused by: java.lang.IllegalArgumentException: 'beanName' must not be empty
at org.springframework.util.Assert.hasText(Assert.java:162)
at org.springframework.beans.factory.config.RuntimeBeanReference.(RuntimeBeanReference.java:58)
at org.springframework.beans.factory.config.RuntimeBeanReference.(RuntimeBeanReference.java:46)
at org.springframework.transaction.config.AnnotationDrivenBeanDefinitionParser.parseInternal(AnnotationDrivenBeanDefinitionParser.java:76)
at org.springframework.beans.factory.xml.AbstractBeanDefinitionParser.parse(AbstractBeanDefinitionParser.java:59)
at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
Peter Ledbrook (blog author) says:
Added on June 1st, 2011 at 9:15 amJerry: you're better off asking support questions on the user mailing list. In this particular case, I think you should probably raise the logging level to 'debug' for the "org.springframework" package because it's not clear which bean name is empty.
Donal says:
Added on June 15th, 2011 at 4:32 amThanks a lot for the post Peter. I notice you haven't mentioned installing any of the JPA plugins. Is there any benefit to installing one of the JPA plugins if we follow the approach outlined in this post?
Jerry Kurian says:
Added on June 15th, 2011 at 4:54 amThanks for your help Peter. The security jars turned out to be the problem once more.
Overall, it seems too difficult to make an existing maven project work with a new Grails app, since Grails does not seem to work too well with Maven out of the box.
Thanks for the post.
Peter Ledbrook (blog author) says:
Added on June 15th, 2011 at 5:10 am@Donal: The GORM-JPA plugin is only useful if you have to use JPA directly rather than Hibernate.
@Jerry: Complications do arise, in particular around plugins. We're investigating improving the support in Grails 1.4. One of our users is also working on a blog post about the Grails/Maven integration and how to get it to work. If I remember, I'll post a link here.
BTW, what do you mean by "an existing Maven project" in relation to a new Grails application? Are you trying to get the Grails app to use the artifact built by the Maven project?
Jerry Kurian says:
Added on June 15th, 2011 at 6:14 amYes, i have a grails app created as a maven project and i am trying to reuse existing maven artifacts.
My application has a modular maven structure and i am trying to reuse the entire back end which is a spring-JPA modular project. I was hoping it would be fairly straight forward to replace the existing struts 2 project with a grails one, but that's not been the case. You are right, most of the problems arise when trying to install and use plugins.
Also, the eclipse IDE seems to loose the grails nature (at least most of it) once the project is created as a maven project. This then makes it very difficult to be as productive with grails as you would expect it to be.
Donal says:
Added on June 15th, 2011 at 6:30 am@Peter: Thanks for your response, but I'm not sure I understand the difference. If I have my domain model classes annotated with the javax.persistence annotations such as @Entity and I'm using Hibernate as my JPA provider (implmementation), does that mean I'm using JPA directly or Hibernate?
Donal says:
Added on June 15th, 2011 at 6:34 am@Peter I'm not sure I understand the difference between the two. If my domain model classes are annotated with javax.persistence annotations such as @Entity and I'm using Hibernate as my JPA provider, am I using JPA directly or Hibernate? Thanks again.
Peter Ledbrook (blog author) says:
Added on June 17th, 2011 at 6:31 am@Donal: if your domain classes are annotated with javax.persistence annotation but you configure them via the Hibernate mapping file, then you are using standard GORM/Hibernate (there is no EntityManager involved). If you need to use JPA natively (without Hibernate), then GORM-JPA is the plugin you need. So basically GORM-JPA is intended to be a drop in replacement for the Hibernate plugin.
Donal says:
Added on July 25th, 2011 at 5:14 pm@Peter – thanks again for your help. Sorry to labour the point, but are you saying that you can either:
1) Configure the JPA-annotated classes in grails-app/conf/hibernate/hibernate.cfg.xml and use the standard GORM/Hibernate plugin (the one that's installed in a Grails app by default).
2) Install the GORM-JPA plugin without configuring the JPA-annotated classes in grails-app/conf/hibernate/hibernate.cfg.xml
Is there any difference in the functionality available when choosing (1) or (2)?
I started trying to integrate a JPA-domain layer with a Grails app and immediately ran into this problem: http://stackoverflow.com/questions/6822797/grails-and-jpa-integration
If you have any idea what the cause might be, I'd be very grateful if you'd let me know.
Thanks Again,
Donal
Peter Ledbrook (blog author) says:
Added on July 27th, 2011 at 2:44 am@Donal: that's correct (points 1 & 2). The Hibernate plugin is much more widely used and has more functionality than GORM-JPA currently. The GORM-JPA plugin still needs some more development.
I see your StackOverflow question has been answered. Grails 2.0 M1 will be out shortly (should be this week) and we're aiming for GA mid-September.
Donal says:
Added on July 27th, 2011 at 3:30 am@Peter – thanks again
One last (hopefully) question is about how to create the app context. Currently I have 3 projects
- Grails web project
- Java service project
- Java domain project
The Grails project picks up the JAR files for the Java projects from the Maven repo. The service JAR already contains an appContext.xml file that defines beans such as:
- LocalContainerEntityManagerFactoryBean
- PersistenceAnnotationBeanPostProcessor
- DataSource
- JpaTransactionManager
The business service beans are not explicitly defined in the XML file. Instead the classes are annotated with @Component, @Service, etc. and Spring picks them up from the classpath due to the following definition in appContext.xml:
Presumably I could redefine all my beans in resources.groovy, but I'd prefer to use the XML file "as is". I tried adding the following to resources.groovy
beans = {
importBeans('classpath:/appContext.xml')
}
Grails seems to create beans for the DataSource, transaction manager, etc. but not for the classes annotated @Component, @Service, etc.
Is it advisable to import appContext.xml into resources.groovy like this, and if so, how can I get beans created for the annotated classes?
Donal says:
Added on July 27th, 2011 at 5:13 amThere's a line missing from the previous comment. After:
"…Spring picks them up from the classpath due to the following definition in appContext.xml:"
The following should appear:
<context:component-scan base-package="com.service.impl"/>
Peter Ledbrook (blog author) says:
Added on July 27th, 2011 at 5:34 amYou probably just need to declare the annotation base package in Config.groovy:
Note that you could also put appContext.xml in grails-app/conf/spring and rename it to resources.xml.
Donal says:
Added on July 27th, 2011 at 6:00 amThanks again Peter. Do you know if there are any sample Grails-JPA 2.0 applications that demonstrate how to integrate a JPA 2.0 domain model (and Spring config) into a new Grails app?
Apart from this blog post, the only substantial information I've been able to find is this article: http://bit.ly/qJLYVO
which is 2-years-old and only covers JPA 1.0. BTW, the GORM-JPA plugin docs state:
"Dynamic finders are supported by the plugin, but since JPA 1.0 doesn't support Criteria, criteria queries are not."
Does this mean that this plugin only supports JPA 1.0? If so, then is the GORM Hibernate plugin (the approach detailed in this article), the only option for JPA 2.0?
Peter Ledbrook (blog author) says:
Added on July 27th, 2011 at 7:59 amI don't, sorry. I suspect not enough people use JPA-based models – certainly no one that writes articles.
As for GORM-JPA, that still requires some more work to get it supporting criteria queries. The Hibernate plugin is the best option at the moment, although the GORM-JPA work is provisionally schedule for after the Grails 2.0 release.
Donal says:
Added on July 27th, 2011 at 8:34 amMaybe I'll step up to the plate and write a JPA 2.0-Grails tutorial using my current project as an exemplar. Thanks again for your feedback, would you mind letting me know if the following is an accurate summary of our discussion?
Hibernate Plugin
—————
- JPA classes configured in hibernate.cfg.xml
- Constraints configured in src/java
- Provides full GORM functionality
- Supports JPA 2.0
GORM-JPA Plugin
—————
- Provides limited GORM functionality, e.g. no countBy, listOrderBy dynamic finders or criteria queries
- Suppprts JPA 1.0 only (not sure about this??)
Spring
======
Existing Spring config can either be imported from classpath into resources.groovy using the BeanBuilder's importBeans method, or copied to grails-app/conf/spring
Packages that should be scanned for annotated beans must be configured in Config.groovy
Grails
======
Support for JPA 2.0 with Hibernate 3.6 is not available in versions of Grails prior to 2.0
Donal says:
Added on July 28th, 2011 at 4:11 pmI created conf/hibernate/hibernate.cfg.xml with a list of my JPA-annotated classes, but it seems like Grails doesn't recognise them as domain classes because when I start the grails console and evaluate:
grailsApplication.domainClasses
I get an empty List. Also, if I run the following on the command-line:
grails generate-all com.model.User
Grails fails to find a domain class with this name. Is there some other step necessary for Grails to recognise the JPA-annotated classes as domains?
If you're willing to take a look, the app is available here:
http://www.iol.ie/~murtaghd/grails.zip
Donal says:
Added on September 11th, 2011 at 6:51 am@Peter I eventually realised that I need to do my persistence using the JPA EntityManager rather than Hibernate. Based on some of your previous remarks, I should use the GORM-JPA plugin. However, judging by the example persistence.xml shown on that plugin's page, it looks like it only supports JPA 1.0, is that right?
Peter Ledbrook (blog author) says:
Added on September 12th, 2011 at 5:43 am@Donal It's only been tested with JPA 1.0. Even if it works with JPA 2.0, you still won't get criteria queries until the plugin has been updated. Hope that helps.
Donal says:
Added on September 12th, 2011 at 6:32 am@Peter – thanks I'll see if I can get it working with JPA 2.0 and post the results here. Do you know if you can use GORM constraints (in the manner described above) when using JPA directly, i.e. with the GORM-JPA plugin installed and configured?
Peter Ledbrook (blog author) says:
Added on September 12th, 2011 at 9:30 am@Donal GORM constraints are supported by the old plugin, but apparently not very well. Graeme has been working recently on the new one though, and it's apparently passing the GORM TCK. That will allow you use standard GORM constraints, mappings and criteria queries. Keep an eye out for a release (hopefully soon).
Martin Homik says:
Added on September 28th, 2011 at 7:24 amHow do you unit test constraints in this scenario? I tried "mockForConstraintsTests", but Grails seems not to add the constraints to the domain class such that validation always returns 'true'. Any idea?
Peter Ledbrook (blog author) says:
Added on September 28th, 2011 at 9:19 am@Martin I'm afraid unit tests won't work here, even in Grails 2.0. You will have to write integration tests. Fortunately, the improved interactive mode in Grails 2.0 will make repeated execution of integration tests much quicker than with Grails 1.3.
Myong Chong says:
Added on February 14th, 2012 at 12:02 pm@Peter Is there a tool or easy way to convert Hibernate mapped models to GORM models? I would like to take advantage of my existing Hibernate models (without re-writing them to GORM models by hand) but also be able to write unit tests with them.
Peter Ledbrook (blog author) says:
Added on February 22nd, 2012 at 6:14 am@Myong The only approach I can think of is to use the Reverse Engineer plugin to build the GORM model from the database schema: http://grails.org/plugin/db-reverse-engineer
ew says:
Added on May 4th, 2012 at 2:42 pmHi,
cool article, Im also reusing a java hibernate model in a grails app. I've solved most issues but have problem with grails not figuring out that a column is called 'userId'. The generated sql shows 'user_id'
heres the mapping in the java entity
@OneToOne
@JoinTable(
name = "ql_user2hotel",
joinColumns = {@JoinColumn(name = "hotelId")},
inverseJoinColumns = {@JoinColumn(name = "userId")}
)
private User user;
I dont really want to touch the java entities (as im copying them from one module to another in my during my buiid lifecycle), so my question is this: Is it possible to define a new file to override the mapping via groovy meta magic a bit like you do above for the constraints?
or is there another way around this ?
hope you can help
thanks
ew says:
Added on May 5th, 2012 at 9:08 amsolved this thanks to the forums the way to do it is with the following in DataSource.groovy:
hibernate {
…
naming_strategy = org.hibernate.cfg.DefaultNamingStrategy
}