博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Hibernate集成示例教程(Spring 4 + Hibernate 3和Hibernate 4)
阅读量:2532 次
发布时间:2019-05-11

本文共 14857 字,大约阅读时间需要 49 分钟。

Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework. That’s why Spring Hibernate combination is used a lot in enterprise applications. Recently I have written a lot for and , so a post for spring hibernate integration was due for long time.

Spring是最常用的Java EE框架之一,而Hibernate是最流行的ORM框架。 这就是为什么Spring Hibernate组合在企业应用程序中大量使用的原因。 最近,我为和写了很多文章,因此针对 集成的帖子由来已久。

春天冬眠 (Spring Hibernate)

Today in this tutorial, we will use Spring 4 and integrate it with Hibernate 3 and then update the same project to use Hibernate 4. Since there are a lot of versions for Spring and Hibernate both and Spring ORM artifact supports both Hibernate 3 and Hibernate 4, it’s good that I list all the dependencies I have used in my project.

今天,在本教程中,我们将使用Spring 4并将其与Hibernate 3集成,然后更新同一项目以使用Hibernate4。由于Spring和Hibernate都有很多版本,并且Spring ORM工件同时支持Hibernate 3和Hibernate 4。 ,最好列出我在项目中使用过的所有依赖项。

Note that I have noticed that all spring and hibernate versions are not compatible, below versions have worked for me so I think they are compatible. If you are using some other versions and getting java.lang.NoClassDefFoundError, then it means that they are not compatible. Mostly it’s because Hibernate classes are moved from one package to another causing this error. For example org.hibernate.engine.FilterDefinition class is moved to org.hibernate.engine.spi.FilterDefinition in latest hibernate versions.

请注意,我注意到所有Spring和Hibernate版本都不兼容,以下版本对我有用,因此我认为它们兼容。 如果您正在使用其他版本并获取java.lang.NoClassDefFoundError ,则意味着它们不兼容。 通常是因为Hibernate类从一个包移动到另一个包导致此错误。 例如,在最新的Hibernate版本中, org.hibernate.engine.FilterDefinition类已移至org.hibernate.engine.spi.FilterDefinition

  • Spring Framework Version: 4.0.3.RELEASE

    Spring Framework版本:4.0.3.3
  • Hibernate Core and Hibernate EntityManager Version: 3.6.9.Final and 4.3.5.Final

    Hibernate Core和Hibernate EntityManager版本:3.6.9.Final和4.3.5.Final
  • Spring ORM Version: 4.0.3.RELEASE

    Spring ORM版本:4.0.3.3

数据库设置 (Database Setup)

I am using MySQL database for my project, so below setup.sql script will create the necessary table for this example.

我正在为项目使用MySQL数据库,因此在setup.sql脚本下面将为该示例创建必要的表。

CREATE TABLE `Person` (  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,  `name` varchar(20) NOT NULL DEFAULT '',  `country` varchar(20) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;commit;

Spring Hibernate集成示例项目结构 (Spring Hibernate Integration Example Project Structure)

Below image shows the final project structure, we will go through each of the components one by one.

下图显示了最终的项目结构,我们将逐一介绍每个组件。

Maven依赖 (Maven Dependencies)

We will first look into our pom.xml file for all the required dependencies and their versions.

我们将首先在pom.xml文件中查找所有必需的依赖项及其版本。

4.0.0
org.springframework.samples
SpringHibernateExample
0.0.1-SNAPSHOT
1.6
UTF-8
UTF-8
4.0.3.RELEASE
3.6.9.Final
1.0.13
1.7.5
org.springframework
spring-context
${spring-framework.version}
org.springframework
spring-tx
${spring-framework.version}
org.springframework
spring-orm
${spring-framework.version}
org.slf4j
slf4j-api
${slf4j.version}
compile
ch.qos.logback
logback-classic
${logback.version}
runtime
org.hibernate
hibernate-entitymanager
${hibernate.version}
org.hibernate
hibernate-core
${hibernate.version}
mysql
mysql-connector-java
5.1.9
commons-dbcp
commons-dbcp
1.4

Important Dependencies for Spring and Hibernate Integration Project are:

Spring和Hibernate集成项目的重要依赖项是:

  • spring-context and spring-tx for core Spring functionalities. Notice that I am using version 4.0.3.RELEASE.

    spring-context和spring-tx用于核心Spring功能。 请注意,我正在使用版本4.0.3.RELEASE。
  • spring-orm dependency for Spring ORM support, it’s required for hibernate integration in our spring project.

    spring-orm依赖关系支持Spring ORM,在我们的Spring项目中进行Hibernate集成是必需的。
  • hibernate-entitymanager and hibernate-core dependencies for Hibernate framework. Notice that version is 3.6.9.Final, for using Hibernate 4 all we need is to change it to 4.3.5.Final as commented in above pom.xml file.

    Hibernate框架的hibernate-entitymanager和hibernate-core依赖项。 注意,版本是3.6.9.Final,要使用Hibernate 4,我们需要将其更改为4.3.5.Final,如上pom.xml文件中所述。
  • mysql-connector-java for MySQL driver for database connection.

    mysql-connector-java用于数据库连接MySQL驱动程序。

模型类或实体Bean (Model Class or Entity Bean)

We can use Hibernate XML based mapping as well as JPA annotation based mapping. Here I am using JPA annotations for mapping because hibernate provides JPA implementation.

我们可以使用基于Hibernate XML的映射以及基于JPA注释的映射。 我在这里使用JPA注释进行映射,因为hibernate提供了JPA实现。

package com.journaldev.model;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;/** * Entity bean with JPA annotations * Hibernate provides JPA implementation * @author pankaj * */@Entity@Table(name="Person")public class Person {	@Id	@Column(name="id")	@GeneratedValue(strategy=GenerationType.IDENTITY)	private int id;		private String name;		private String country;	public int getId() {		return id;	}	public void setId(int id) {		this.id = id;	}	public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public String getCountry() {		return country;	}	public void setCountry(String country) {		this.country = country;	}		@Override	public String toString(){		return "id="+id+", name="+name+", country="+country;	}}

DAO类 (DAO Classes)

We will implement two methods in our DAO classes, first to save the Person object into table and second that will fetch all the records from the table and returns the list of Persons.

我们将在DAO类中实现两个方法,第一个方法将Person对象保存到表中,第二个将从表中获取所有记录并返回Person列表。

package com.journaldev.dao;import java.util.List;import com.journaldev.model.Person;public interface PersonDAO {	public void save(Person p);		public List
list(); }

Above DAO class implementation would be like below.

上面的DAO类实现如下。

package com.journaldev.dao;import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import com.journaldev.model.Person;public class PersonDAOImpl implements PersonDAO {	private SessionFactory sessionFactory;    public void setSessionFactory(SessionFactory sessionFactory) {        this.sessionFactory = sessionFactory;    }    	@Override	public void save(Person p) {		Session session = this.sessionFactory.openSession();		Transaction tx = session.beginTransaction();		session.persist(p);		tx.commit();		session.close();	}	@SuppressWarnings("unchecked")	@Override	public List
list() { Session session = this.sessionFactory.openSession(); List
personList = session.createQuery("from Person").list(); session.close(); return personList; }}

Notice that this is the only place where we are using Hibernate related classes. This pattern makes our implementation flexible and easy to migrate from one technology to another. For example, if we want to use iBatis ORM framework, all we need is to provide a DAO implementation for iBatis and then change the spring bean configuration file.

注意,这是我们使用Hibernate相关类的唯一地方。 这种模式使我们的实现灵活且易于从一种技术迁移到另一种技术。 例如,如果我们要使用iBatis ORM框架,我们所需要做的就是为iBatis提供DAO实现,然后更改spring bean配置文件。

In above example, I am using Hibernate session transaction management. But we can also use Spring declarative transaction management using @Transactional annotation, read more at .

在上面的示例中,我正在使用Hibernate会话事务管理。 但是我们也可以使用通过@Transactional注释的Spring声明式事务管理,更多内容请@Transactional

用于Hibernate 3集成的Spring Bean配置文件 (Spring Bean Configuration File for Hibernate 3 Integration)

Let’s first look at the spring bean configurations we need for Hibernate 3 integration, we will look into detail later on.

首先让我们看一下Hibernate 3集成所需的spring bean配置,稍后我们将详细介绍。

com.journaldev.model.Person
org.hibernate.dialect.MySQLDialect
thread
false

There are two ways we can provide database connection details to Hibernate, first by passing everything in hibernateProperties and second by creating a DataSource and then passing it to hibernate. I prefer the second approach, that’s why we have Apache Commons DBCP dependency to create a BasicDataSource by setting database connection properties.

我们可以通过两种方式向Hibernate提供数据库连接详细信息,一种是将所有内容传递给hibernateProperties ,其次是创建一个DataSource,然后将其传递给hibernate。 我更喜欢第二种方法,这就是为什么我们有Apache Commons DBCP依赖项来通过设置数据库连接属性来创建BasicDataSource的原因。

For Spring and Hibernate 3 integration, Spring ORM provides two classes – org.springframework.orm.hibernate3.LocalSessionFactoryBean when hibernate mappings are XML based and org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean for annotations based mapping. I have provided simple bean configuration of LocalSessionFactoryBean in comments, if you are using XML based mappings. AnnotationSessionFactoryBean extends LocalSessionFactoryBean class, so it has all the basic properties for hibernate integration.

对于Spring和Hibernate 3集成,当Hibernate映射基于XML时, Spring ORM提供两个类– org.springframework.orm.hibernate3.LocalSessionFactoryBeanorg.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean用于基于注释的映射。 如果您使用的是基于XML的映射,那么我已在注释中提供了LocalSessionFactoryBean简单bean配置。 AnnotationSessionFactoryBean扩展了LocalSessionFactoryBean类,因此它具有用于Hibernate集成的所有基本属性。

The properties are self understood and mostly hibernate related, so I will not go into much detail for them. But if you are wondering from where hibernateProperties, annotatedClasses are coming, you need to look into the bean class source code.

这些属性是可以自我理解的,并且大多与Hibernate有关,因此我将不对其进行详细介绍。 但是,如果您想知道hibernatePropertiesannotatedClasses来自何处,则需要研究bean类的源代码。

Notice the bean definition of personDAO, like I said earlier if we have to switch to some other ORM framework, we need to change the implementation class here and set any other properties we need.

请注意personDAO的bean定义,就像我之前说的,如果我们必须切换到其他ORM框架,则需要在此处更改实现类并设置所需的任何其他属性。

Spring 4 Hibernate 3测试程序 (Spring 4 Hibernate 3 Test Program)

Our setup is ready now, let’s write a simple program to test our application.

现在我们的设置已经准备就绪,让我们编写一个简单的程序来测试我们的应用程序。

package com.journaldev.main;import java.util.List;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.journaldev.dao.PersonDAO;import com.journaldev.model.Person;public class SpringHibernateMain {	public static void main(String[] args) {		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");				PersonDAO personDAO = context.getBean(PersonDAO.class);				Person person = new Person();		person.setName("Pankaj"); person.setCountry("India");				personDAO.save(person);				System.out.println("Person::"+person);				List
list = personDAO.list(); for(Person p : list){ System.out.println("Person List::"+p); } //close resources context.close(); }}

When we execute above program, we get a lot of output related to Hibernate because I haven’t setup logging properly, but that’s out of scope of this tutorial. However we get following output generated by our program.

当我们执行上述程序时,由于没有正确设置日志记录,因此会得到许多与Hibernate相关的输出,但这超出了本教程的范围。 但是,我们得到了程序生成的以下输出。

Person::id=3, name=Pankaj, country=IndiaPerson List::id=1, name=Pankaj, country=IndiaPerson List::id=2, name=Pankaj, country=IndiaPerson List::id=3, name=Pankaj, country=India

Spring 4 Hibernate 4集成更改 (Spring 4 Hibernate 4 integration changes)

Now let’s change our application to use Hibernate 4 instead of Hibernate 3. For this migration, we need to make only following configuration changes.

现在,让我们将应用程序更改为使用Hibernate 4而不是Hibernate3。对于此迁移,我们仅需要进行以下配置更改。

  1. Change the hibernate version to 4.3.5.Final in the pom.xml file, as shown in comments above.

    将pom.xml文件中的Hibernate版本更改为4.3.5.Final,如上面的注释所示。
  2. Change the spring bean configuration file, till now you must have figured out that Spring bean configuration file is the key for integration of spring and hibernate framework. Below spring bean configuration file will work for Spring 4 and Hibernate 4 versions.
    com.journaldev.model.Person
    org.hibernate.dialect.MySQLDialect
    thread
    false

    For hibernate 4, we need to use org.springframework.orm.hibernate4.LocalSessionFactoryBean for SessionFactory bean, Spring ORM has merged both the classes for Hibernate 3 and there is a single class now, this is good to avoid confusion. All the other configurations are same as before.

    对于hibernate 4,我们需要为SessionFactory bean使用org.springframework.orm.hibernate4.LocalSessionFactoryBean ,Spring ORM合并了Hibernate 3的两个类,现在有一个类,这样可以避免混淆。 所有其他配置与以前相同。

That’s it, our project is successfully migrated to Hibernate 4, neat isn’t it. Just change the SpringHibernateMain class to use spring4.xml for beans configuration and it will work fine, you will get same output as before.

就是这样,我们的项目已成功迁移到Hibernate 4,不是吗? 只需将SpringHibernateMain类更改为使用spring4.xml进行bean配置,它将正常工作,您将获得与以前相同的输出。

You can download the final project from below link and play around with more configurations to learn more.

您可以从下面的链接下载最终项目,并进行更多配置以了解更多信息。

翻译自:

转载地址:http://gbqzd.baihongyu.com/

你可能感兴趣的文章
考研经验交流
查看>>
手游助手应用源码项目
查看>>
职场心得笔记
查看>>
Android context(Application/Activity)与内存泄露
查看>>
mysql 行转列
查看>>
jquery easyui 经验
查看>>
Kafka官方文档翻译——设计
查看>>
本地推送
查看>>
免费的在线文档翻译神器
查看>>
RabbitMQ --- Publish/Subscribe(发布/订阅)
查看>>
细思极恐-你真的会写java吗
查看>>
Jquery 多选下拉列表插件jquery multiselect之如何去掉默认选中项1
查看>>
安装apache Unable to correct problems, you have held broken packages
查看>>
搭建Sphinx环境及文档
查看>>
实验随笔
查看>>
Weapsy分析终
查看>>
8个免费实用的C++GUI库(转载)
查看>>
d010: 分离自然数
查看>>
软件工程的实践项目的自我目标
查看>>
Java8 in action(1) 通过行为参数化传递代码--lambda代替策略模式
查看>>