这部分介绍Spring和ORM框架的整合。虽然Hibernate在开源ORM 社区很流行,但本文会以MyBatis为例讲解。另外关于MyBatis和Hibernate的优劣之分是没有意义的,主要是看实际需求,有兴趣可以百度、谷歌查看。
首先配置环境,你得有mybatis和mybatis-spring在Spring工程的build path里,如果你使用的是Maven,只需添加下面的依赖:(都是目前最新版本)
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency>
我们知道,MyBatis应用的核心是SqlSessionFactory,在Spring里也需要定义这样一个bean,
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean>
<jdbc:embedded-database id="dataSource" type="H2"> <jdbc:script location="classpath:schema.sql" /> <jdbc:script location="classpath:data.sql" /> </jdbc:embedded-database>
create table spitter ( id identity, username varchar(25) not null, password varchar(25) not null, fullname varchar(100) not null, email varchar(50) not null, update_by_email boolean not null );
package org.chen.mybatis.mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.chen.domain.Spitter; public interface SpitterMapper { @Select("SELECT * from spitter where email = #{email}") Spitter getSpitter(@Param("email") String email); }
然后使用MapperFactoryBean将该接口注册到Spring,
<bean id="spitterMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="org.chen.mybatis.mapper.SpitterMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
如,
public class TestService { private SpitterMapper spitterMapper; public void setSpitterMapper(SpitterMapper spitterMapper) { this.spitterMapper = spitterMapper; } public void getSpitterByEmail(String email){ Spitter spitter = spitterMapper.getSpitter(email); System.out.println("spitter is " + spitter.getFullName()); } }
原文地址:http://blog.csdn.net/chenloveit/article/details/38857581