Spring : 征服数据库 (两)

时间:2023-03-09 22:37:51
Spring : 征服数据库 (两)

本节介绍Spring和ORM集成框架。尽管Hibernate在开源ORM 社区很受欢迎。但是,本文将MyBatis案例解说。也MyBatis和Hibernate好坏是没有意义的,主要看实际需求,有兴趣的可以百度、歌查看。

首先配置环境。你得有mybatis和mybatis-spring在Springproject的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());
}
}

至此,基本操作根据可以完毕。

版权声明:本文博客原创文章。博客,未经同意,不得转载。