本文共 3637 字,大约阅读时间需要 12 分钟。
As part of the , we have a lab application that we use to show how to integrate Spring and JPA/Hibernate together. We have just upgraded it to Spring 3.1 / Hibernate 4.1, and thought we should share a few tips.
The configuration sample below is based on Maven (but you can easily convert it to Gradle if needed). Inside your POM, you should specify the latest versions of Spring and Hibernate (you might need to declare more Spring dependencies depending on which Spring components you're using).
org.springframework spring-orm 3.2.0.RELEASE org.hibernate hibernate-entitymanager 4.1.9.Final
The cglib dependency is not always needed. You will find more details on that at the end of this blog entry.
Spring provides support for several versions of Hibernate, so you need to specify explicitly which version you're using.
With Hibernate 4:
...
If you were to work with Hibernate 3, you would have instead:
...
(the package path is different according to whether you wish to use Hibernate 3 or Hibernate 4)
When working with Hibernate, there are 2 common ways of writing your mapping: XML and annotations.
Spring-Hibernate 3 integration allows you to configure 2 kinds of SessionFactoryBean:
With Spring 3.1 and Hibernate 4, things are now simpler: there is only one SessionFactoryBean called LocalSessionFactoryBean. It works with both annotation-based mapping and xml-based mapping.
If you followed those 2 steps carefully, you should have a running application already.
As an alternative of using Hibernate directly, you can also use JPA as an abstraction layer on top of Hibernate. Here is an example:
jpa/config
The answer is likely to be a "yes". It is actually common that Spring would need it under the hood. Here are some examples:
Using with Spring is an interesting alternative to xml-based and annotation-based configuration. So how to work with Spring and Hibernate using Java configuration? A new class called LocalSessionFactoryBuilder makes things pretty easy.
@Beanpublic SessionFactory sessionFactory() { return new LocalSessionFactoryBuilder(dataSource()) .addAnnotatedClasses(Person.class, Account.class) .buildSessionFactory();}
LocalSessionFactoryBuilder subclasses Hibernate's own Configuration class, and as the name suggests, provides a convenient builder-style API for use within Spring @Configuration classes.
All the above code samples are available here:
转载地址:http://enpob.baihongyu.com/