1. Overview
1.概述
This article will focus on setting up Hibernate 3 with Spring – we’ll look at how to use both XML and Java configuration to set up Spring with Hibernate 3 and MySQL.
本文将重点介绍用Spring设置Hibernate 3–我们将看看如何使用XML和Java配置来设置Spring与Hibernate 3和MySQL。
Update: this article is focused on Hibernate 3. If you’re looking for the current version of Hibernate – this is the article focused on it.
更新:这篇文章专注于Hibernate 3。如果你正在寻找当前版本的Hibernate–这是关注它的文章。
2. Java Spring Configuration for Hibernate 3
2.JavaHibernate 3的Spring配置
Setting up Hibernate 3 with Spring and Java config is straightforward:
用Spring和Java配置来设置Hibernate 3是很简单的。
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.google.common.base.Preconditions;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-mysql.properties" })
@ComponentScan({ "com.baeldung.spring.persistence" })
public class PersistenceConfig {
@Autowired
private Environment env;
@Bean
public AnnotationSessionFactoryBean sessionFactory() {
AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.baeldung.spring.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource restDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
}
};
}
}
Compared to the XML Configuration – described next – there is a small difference in the way one bean in the configuration access another. In XML there is no difference between pointing to a bean or pointing to a bean factory capable of creating that bean. Since the Java configuration is type-safe – pointing directly to the bean factory is no longer an option – we need to retrieve the bean from the bean factory manually:
与XML配置相比–接下来描述–配置中的一个Bean访问另一个Bean的方式有一点区别。在XML中,指向一个Bean或指向一个能够创建该Bean的Bean工厂之间没有区别。由于Java配置是类型安全的–直接指向Bean工厂不再是一种选择–我们需要从Bean工厂手动检索Bean。
txManager.setSessionFactory(sessionFactory().getObject());
3. XML Spring Configuration for Hibernate 3
3.用于Hibernate 3的XML Spring配置
Similarly, we can set up Hibernate 3 with XML config as well:
同样地,我们也可以用XML配置来设置Hibernate 3。
<context:property-placeholder location="classpath:persistence-mysql.properties" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.baeldung.spring.persistence.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.pass}" />
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
Then, this XML file is bootstrapped into the Spring context using a @Configuration class:
然后,使用@Configuration类将这个XML文件引导到Spring上下文中。
@Configuration
@EnableTransactionManagement
@ImportResource({ "classpath:persistenceConfig.xml" })
public class PersistenceXmlConfig {
//
}
For both types of configuration, the JDBC and Hibernate specific properties are stored in a properties file:
对于这两种类型的配置,JDBC和Hibernate的特定属性都存储在一个属性文件中。
# jdbc.X
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate_dev?createDatabaseIfNotExist=true
jdbc.user=tutorialuser
jdbc.pass=tutorialmy5ql
# hibernate.X
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
4. Spring, Hibernate and MySQL
4.Spring、Hibernate和MySQL
The example above uses MySQL 5 as the underlying database configured with Hibernate – however, Hibernate supports several underlying SQL Databases.
上面的例子使用MySQL 5作为配置了Hibernate的底层数据库 – 但是,Hibernate支持多个底层SQL数据库。
4.1. The Driver
4.1.司机
The Driver class name is configured via the jdbc.driverClassName property provided to the DataSource.
驱动程序类的名称是通过提供给DataSource的jdbc.driverClassName属性配置的。
In the example above, it is set to com.mysql.jdbc.Driver from the mysql-connector-java dependency we defined in the pom, at the start of the article.
在上面的例子中,它被设置为com.mysql.jdbc.Driver,来自我们在文章开头定义的pom中的mysql-connector-java依赖。
4.2. The Dialect
4.2.方言
The Dialect is configured via the hibernate.dialect property provided to the Hibernate SessionFactory.
方言是通过提供给HibernateSessionFactory的hibernate.dialect属性配置的。
In the example above, this is set to org.hibernate.dialect.MySQL5Dialect as we are using MySQL 5 as the underlying Database. There are several other dialects supporting MySQL:
在上面的例子中,这被设置为org.hibernate.dialect.MySQL5Dialect,因为我们正在使用MySQL 5作为底层数据库。有几种支持MySQL的其他方言。
- org.hibernate.dialect.MySQL5InnoDBDialect – for MySQL 5.x with the InnoDB storage engine
- org.hibernate.dialect.MySQLDialect – for MySQL prior to 5.x
- org.hibernate.dialect.MySQLInnoDBDialect – for MySQL prior to 5.x with the InnoDB storage engine
- org.hibernate.dialect.MySQLMyISAMDialect – for all MySQL versions with the ISAM storage engine
Hibernate supports SQL Dialects for every supported Database.
Hibernate 支持每个支持的数据库的SQL方言。
5. Usage
5.使用方法
At this point, Hibernate 3 is fully configured with Spring and we can inject the raw Hibernate SessionFactory directly whenever we need to:
在这一点上,Hibernate 3已经与Spring完全配置好了,我们可以在需要的时候直接注入原始HibernateSessionFactory。
public abstract class FooHibernateDAO{
@Autowired
SessionFactory sessionFactory;
...
protected Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
}
6. Maven
6.Maven
To add the Spring Persistence dependencies to the pom, please see the Spring with Maven example – we’ll need to define both spring-context and spring-orm.
要在Pom中添加Spring Persistence的依赖项,请参见Spring with Maven 示例 – 我们需要同时定义spring-context和spring-orm。
Continuing to Hibernate 3, the Maven dependencies are simple:
继续说Hibernate 3,Maven的依赖性很简单。
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
Then, to enable Hibernate to use its proxy model, we need javassist as well:
然后,为了使Hibernate能够使用其代理模型,我们也需要javassist。
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.18.2-GA</version>
</dependency>
We’re going to use MySQL as our DB for this tutorial, so we’ll also need:
我们将使用MySQL作为本教程的数据库,所以我们还需要。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
<scope>runtime</scope>
</dependency>
And finally, we will not be using the Spring data source implementation – the DriverManagerDataSource; instead, we’ll use a production-ready connection pool solution – Tomcat JDBC Connection Pool:
最后,我们将不使用Spring的数据源实现–DriverManagerDataSource;相反,我们将使用一个生产就绪的连接池解决方案–Tomcat JDBC连接池。
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>7.0.55</version>
</dependency>
7. Conclusion
7.结论
In this example, we configured Hibernate 3 with Spring – both with Java and XML configuration. The implementation of this simple project can be found in the GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.
在这个例子中,我们用Spring配置了Hibernate 3–既用Java又用XML配置。这个简单项目的实现可以在GitHub项目中找到 – 这是一个基于Maven的项目,所以应该很容易导入并按原样运行。