1. 搭建
1.1 核心配置文件
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN“
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/xx/mapper/UserMapper.xml"/>
</mappers>
</configuration>
1.2 mapper配置文件
<?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="userMapper">
<select id="findAll" resultType="com.xx.domain.User">
select * from User
</select>
</mapper>
1.3 核心配置文件屬性介紹
- properties
<!-- 屬性配置文件 引入屬性文件,在配置文件中用${}直接引用 --> <properties resource="dataSource.properties"> <!--自定義屬性--> <property name="dirver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/testdb?useSSL=true&useUnicode=true" /> </properties>
- settings
<settings> <!--開啟二級緩存--> <setting name="cacheEnabled" value="true"/> <!--日志實現(xiàn)--> <setting name="logImpl" value="LOG4J"> </settings>
- typeAliases
<!--別名管理--> <typeAliases> <typeAlias type="com.rm.demo.domain.BookInfo" alias="book" /> <package name="com.rm.demo.domain"> <!--命名空間--> </typeAliases>
- typeHandlers 類型處理器
- objectFactory 對象工廠
- plugins 插件
- environments
- environment
- transactionManager
- datasource
- environment
- databaseIdProvider 數(shù)據(jù)庫廠商標(biāo)識
- mappers
<!--作用:加載映射的辩昆,加載方式有如下幾種:--> <!-- 使用完全限定資源定位符(URL)粥航,例如:不常用--> <mapper url="file:///var/mappers/AuthorMapper.xml"/> <!--使用映射器接口實現(xiàn)類的完全限定類名,例如:不常用--> <mapper class="com.mybatis.builder.AuthorMapper"/> <!--使用相對于類路徑的資源引用疼蛾,例如:可以用枯途,不建議 --> <mapper resource="com/mybatis/builder/AuthorMapper.xml"/> <!--將包內(nèi)的映射器接口實現(xiàn)全部注冊為映射器教寂,例如:--> <package name="com.mybatis.builder"/>
1.4 動態(tài)sql
- where-if
<select id="findByCondition" parameterType="user" resultType="user">
select * from User
<where>
<if test="id!=0">
and id=#{id}
</if>
<if test="username!=null">
and username=#{username}
</if>
</where>
</select>
- foreach-in