myBatis配置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了myBatis配置相关的知识,希望对你有一定的参考价值。
1.读取全局配置文件String resource="mybatis-config.xml";
InputStream is=Resources.getResourceAsStream(resource);
2.创建SqlSessionFactory对象
SqlSessionFactory factory=new SqlSessionFactoryBulider().build(is);
3.创建SqlSession 调用Mapper
SqlSession sqlSession=factory.openSession();
int count=sqlSession.selectOne("方法");
sqlSession.close();
配置文件mybatis-config.xml
(先后顺序有要求
1.properties-2.settings-3.typeAliases(别名)-4.typeHandlers(类型处理器)-5.objectFactory(对象工厂)-6.plugins(插件)-7.environments(环境)-8.mappers(映射器))
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入database.properties文件-->
<properties resource="database.properties"/>
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<typeAliases>
<typeAlias alias="user" type="cn.smbms.pojo.User">
</typeAliases>
<environments default="abc">
<!-- default跟id对应 -->
<environment id="abc">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="Mapper/BillMapper.xml" />
</mappers>
</configuration>
mapper
1.parameterType 传入参数类型
2.resultMap 自定义映射 (外键操作用到)
会自动映射匹配,关闭
<settings><setting name="autoMappingBehavior" value="None"></settings>
PATYIAL 或FULL(包含内部嵌套)
<resultMap type="cn.smbms.pojo.User" id="UserList" >
<result property="id" column="id" />
<result property="userCode" column="userCode" />
<result property="userName" column="userName" />
<result property="phone" column="phone" />
<result property="birthday" column="birthday" />
</resultMap>
复杂类型可以嵌套(只适用1对1)
<association property="role" javaType="Role"> 或<collection property="addressList" ofType="Address"> (区别collection是一个集合列表)
<result XXX/>
</association>
3.resultType 自动映射
4.开启二级缓存
<settings><setting name="cacheEnabled" value="true"/></settings>
以上是关于myBatis配置的主要内容,如果未能解决你的问题,请参考以下文章
mybatis配置MapperScannerConfigurer路径警告
Mybatis 复习 Mybatis 配置 Mybatis项目结构