众所周知,spring框架早已成为java软件开发使用的主流开源开发框架了,一方面也是因为其强大的兼容性,那么mybatis呢,也是java持久层中比较优秀的框架,下面就跟小编一起来看看,在springz中如何整合mybatis呢?
首先为项目做类库准备,由于内容比较多,我们划分成3部分:
1、Spring相关类库。
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.19.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.19.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.19.RELEASE</version> </dependency>
2、数据访问类库。
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.7</version> </dependency>
注意:spring整合mybatis的包“==mybatis-spring==”是由mybatis公司制作 提供的。
3、其它
<dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.11.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%-5p [%C{2}] (%F:%L) - %m%n"
/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="STDOUT" />
</Root>
</Loggers>
</Configuration>mybatis-config.xml
<settings> <setting name="logImpl" value="LOG4J"/> </settings>
使用 MyBatis Generator 工具生成好相应的实体类、映射文件和数据访问接口。
POM.XML配置汇总:(所有依赖为当前最新版)。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.turing.sm</groupId> <artifactId>Java16_Spring_05</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Java16_Spring_05</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- 1、加入Spring相关依赖 --> <!-- Spring基础依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- 加入spring-jdbc依赖,只要在spring中直接或间接用到了jdbc,就必须加入这个依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- 加入AspectJ依赖,只要在spring中用到了AOP,就必须加入这个依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.1.9.RELEASE</version> </dependency> <!-- 2、加入MyBatis相关依赖 --> <!-- 加入MyBatis依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <!-- 加入mybatis-spring,只要在Spring中用到了MyBatis就必须加入这个依赖 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> <!-- 加入mybatis-generator 逆向工程工具依赖包 --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.7</version> </dependency> <!-- 3、加入数据库相关依赖 --> <!-- 加入mysql的驱动依赖 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency> <!-- 加入数据源-DBCP2的依赖 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.7.0</version> </dependency> <!-- 4、加入其它相关依赖 --> <!-- 加入LOG4J的日志框架 --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.12.1</version> </dependency> </dependencies> </project>
其次配置
1、 数据源配置。
@Configuration
@ComponentScan(basePackages = "com.tuling")
public class BeanConfig
{
//配置数据源
@Bean
public DataSource dataSource()
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql:///tuling");
ds.setUsername("root");
ds.setPassword("root");
ds.setInitialSize(5);
ds.setMaxTotal(15);
ds.setMaxIdle(8);
ds.setMinIdle(3);
ds.setMaxWaitMillis(10000);
ds.setValidationQuery("select 1");
return ds;
}
}2、 SqlSessionFactory配置 由于MyBatis对JDBC组件进行了轻量级封装,最终通过SqlSession进行数据访问, 所以我们接下来配置SqlSessionFactory,好让后续的bean能得到SqlSession。
//配置SQLSessionFactory
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception
{
//创建sqlSessionFactoryBean
SqlSessionFactoryBean factoryBean = new
SqlSessionFactoryBean();
//注入数据源
factoryBean.setDataSource(dataSource);
//设置MyBatis相关配置
org.apache.ibatis.session.Configuration cfg =
new org.apache.ibatis.session.Configuration();
//日志
cfg.setLogImpl(Log4j2Impl.class);
//自动驼峰命名转换
cfg.setMapUnderscoreToCamelCase(true);
//懒加载
cfg.setLazyLoadingEnabled(true);
cfg.setAggressiveLazyLoading(false);
//设置别名
cfg.getTypeAliasRegistry()
.registerAliases("com.tuling.domain");
factoryBean.setConfiguration(cfg);
return factoryBean.getObject();
}3、 在上面这段配置中,MyBatis将会得到DBCP数据源,对JDBC中的基础组件进行封 装,最后产生`SqlSessionFactory`实例,交给Spring容器进行管理。对比之前单独 使用MyBatis的配置,从基本内容上来看是一致的,只不过表现方式不一样。 3、 SqlSessionTemplate配置 配置好`SqlSessionFactory`以后,我们就可以使用spring为我们准备的 `SqlSessionTemplate`进行数据访问开发了,在配置`SqlSessionTemplate`的时候 我们需要传入`SqlSessionFactory`进行构造。
//配置SQLSessionTemplate
@Bean
public
SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory)
{
return new SqlSessionTemplate(sqlSessionFactory);
}最后是代码设计 。
1、Mapper(取代Dao)。
1)Mapper接口。
public interface CarMapper
{
Car findById(Integer id);
List < Car > findAll();
void insert(Car car);
void update(Car car);
void delete(Integer id);
}2)Mapper xml配置文件。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tuling.dao.CarMapper">
<resultMap type="Car" id="carMapping">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="type" column="type"/>
<result property="price" column="price"/>
</resultMap>
<select id="findById" parameterType="Integer"
resultType="Car">
select * from car
where id=#{id}
</select>
<select id="findAll" resultMap="carMapping">
select * from car
</select>
<insert id="insert" keyColumn="id" keyProperty="id"
useGeneratedKeys="true" parameterType="Car" >
insert into car values(null,#{name},#{type},#{price})
</insert>
<update id="update" parameterType="Car">
update car set name=#{name},type=#{type},price=#
{price} where id=#{id}
</update>
<delete id="delete" parameterType="Integer">
delete from car where id=#{id}
</delete>
</mapper>3)为了让Spring发现我们配置的Mapper,我们需要在配置类上,添加一个注 解: @MapperScan("com.tuling.dao") 。
2、Service(业务层)
1)接口。
public interface ICarService
{
void add(Car car);
}2)实现类。
@Service
public class CarServiceImpl implements ICarService
{
@Autowired
private SqlSessionTemplate sessionTemplate;
public void add(Car car)
{
sessionTemplate.insert("insert", car);
}
}3、测试类(模拟Controller)。
public static void main(String[] args)
{
ApplicationContext ctx = new
AnnotationConfigApplicationContext(BeanConfig.class);
ICarService carService = ctx.getBean(ICarService.class);
Car car = new Car();
car.setName("比亚迪秦333");
car.setType("桥车");
car.setPrice(100000);
carService.add(car);
}
}那么以上步骤就是spring整合mybatis的完整内容了,如果你还有兴趣了解更多java架构师相关信息话,就记得关注本站消息哦。