这部分介绍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和Spring的整合,不会着重讲解Mybatis的具体用法。
我们知道,MyBatis应用的核心是SqlSessionFactory,在Spring里也需要定义这样一个bean,
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
使用的是SqlSessionFactoryBean创建SqlSessionFactory,并需要注入数据源dataSource,这里的数据源就是Spring里面定义的任意数据源,为了演示方便,使用的是上一篇文章介绍的H2内嵌数据源,
<jdbc:embedded-database id="dataSource" type="H2">
<jdbc:script location="classpath:schema.sql" />
<jdbc:script location="classpath:data.sql" />
</jdbc:embedded-database>
在MyBatis里面,为实现SQL的映射,使用的是XML配置文件或mapper接口。上一篇我们的SQL的模式如下:
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);
}
实际上命名并无要求,但约定是domain+Mapper。在一个方法上面添加注解,这里是 @Select,内容是一个SQL语句, #{email}是参数,用于PrepraredStatement使用。
然后使用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>
现在使用上面这个bean就可以完成关系对象映射了,我们一般把spitterMapper注入到service里面,
如,
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());
}
}
至此,基本操作依据能够完成。