一、全局配置文件
实例:
mybatis_config.xml
<?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>
<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://localhost:3306/mybatis_achang"/>
<property name="username" value="root"/>
<property name="password" value="00000"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="EmployeeDao.xml"/>
</mappers>
</configuration>
1、properties(属性)
作用:通过properties标签引入外部内容
properties标签:和Spring的context:property-placeholder;引用外部配置文件
resource属性:从类路径下引入
url属性:引用磁盘路径或网络路径
dbconfig.properties:
username=root
password=00000
url=jdbc:mysql://localhost:3306/mybatis_achang
driver=com.mysql.jdbc.Driver
mybatis_config.xml
通过${ }动态取出配置文件中的内容
<?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>
<properties resource="dbconfig.properties"/>
<environments default="development">
<environment id="development">
<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="EmployeeDao.xml"/>
</mappers>
</configuration>
2、settings(设置)
settings是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
**举例:**mapUnderscoreToCamelCase
数据库字段名与bean对象属性对应驼峰原则
数据库:login_account
javabean:loginAccount
<configuration>
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
3、typeAliases(类型别名)
推荐还是使用全类名!!!
类型别名:为常用的类型起别名
typeAlias属性:就是为一个javaBean起别名;别名默认就是类名(不区分大小写),配置文件中就可以用别名了
alias属性:指定一个别名
package属性:批量起别名
name属性:指定一个包名,默认别名就是类名
@alias()注解:起别名
<typeAliases>
<typeAlias type="com.achang.bean.Employee" alias="emp"/>//起别名
<package name="com.achang.bean"/>//批量起别名
</typeAliases>
下面是一些为常见的 Java 类型内建的类型别名。它们都是不区分大小写的,注意,为了应对原始类型的命名重复,采取了特殊的命名风格。
4、typeHandlers(类型处理器)
- 无论是 MyBatis 在预处理语句(PreparedStatement)中设置一个参数时,还是从结果集中取出一个值时, 都会用类型处理器将获取的值以合适的方式转换成 Java 类型。
<typeHandlers>
<!--自定义好的类型处理器就这么配置上就好-->
<typeHandler handler="自定义类型处理器全类名"
</typeHandlers>
5、plugins(插件)
- 插件是MyBatis提供的一个非常强大的机制,我们可以通过插件来修改MyBatis的一些核心行为。插件通过动态代理机制,可以介入四大对象的任何一个方法的执行。后面会有专门的章节我们来介绍mybatis运行原理以及插件
•Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
•ParameterHandler (getParameterObject, setParameters)
•ResultSetHandler (handleResultSets, handleOutputParameters)
StatementHandler (prepare, parameterize, batch, update, query)
6、environments(环境)
default属性:默认使用哪个环境;填写某个environment标签的id
environment标签:配置一个具体的环境;每一个环境都需要一个事务管理器和数据源
id属性:当前环境的唯一标识
transactionManager标签:事务管理器
后来数据源、事务控制管理都Spring来做;
<environments default="development">
<environment id="development">
<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>
7、databaseIdProvider(数据库厂商标识)
作用:
mybatis用来考虑数据库移植性的-
name属性:数据库厂商标识
value属性:给数据库厂商标识起别名
MYSQL、Oracle、SQL Server;
mybatis_config.xml
<databaseIdProvider type="DB_VENDOR">
<property name="MYSQL" value="mysql"/>
<property name="SQL Server" value="sqlserver"/>
<property name="Oracle" value="oracle"/>
</databaseIdProvider>
EmployeeDao.xml
databaseId属性:选择数据库厂商别名
<!--能精确匹配就精确匹配,不能就模糊匹配-->
<select id="getEmpById" resultType="com.achang.bean.Employee">
select * from t_employee where id = #{id}
</select>
<select id="getEmpById" resultType="com.achang.bean.Employee" databaseId="mysql">
select * from t_employee where id = #{id}
</select>
<select id="getEmpById" resultType="com.achang.bean.Employee" databaseId="oracle">
select * from t_employee where id = #{id}
</select>
8.mappers(映射器)
<!-- class属性:引用接口全类名
可以将xml和dao接口放在同一个文件目录下,并文件名和接口名相同
resource属性:在类路径下找sql映射文件
url属性:从磁盘和网络路径引用sql映射文件
配合使用:重要的dao写配置;简单的用头注解搞定
package标签:批量注册;要求xml和dao类接口在同一个文件夹下且名字相同(可以使用设置资源文件)
name属性:dao所在的包名
-->
EmployeeAnnotationDao:在dao接口头注解上写对应的sql语句
public interface EmployeeAnnotationDao {
@Select("select * from t_employee where id = #{id}")
public Employee getEmpById(Integer id);
@Update("update t_employee set empname = #{empName},gender = #{gender},email = #{email} where id = #{id}\n")
public int updateEmp(Employee employee);
@Delete("delete from t_employee where id = #{id}")
public boolean deleteEmpById(Integer id);
@Insert("insert into t_employee(empname,gender,email)" +
"values(#{empName},#{gender},#{email}))")
public int insertEmp(Employee employee);
}
使用class导入接口注解头sql语句类
<!--写好的sql映射文件,需要使用mappers注册-->
<mappers>
<mapper class="com.achang.dao.EmployeeAnnotationDao"/>
<package name=""/>
</mappers>
测试:
//通过注解导入sql语句;查询
@Test
public void test5() throws IOException {
SqlSession sqlSession = sqlSessionFactory.openSession();
EmployeeAnnotationDao mapper = sqlSession.getMapper(EmployeeAnnotationDao.class);
System.out.println(mapper.getEmpById(3));
}
二、SQL映射文件
—cache –命名空间的二级缓存配置
—cache-ref – 其他命名空间缓存配置的引用。
—resultMap – 自定义结果集映射
—parameterMap – 已废弃!老式风格的参数映射,原本是做复杂参数映射的
—sql –抽取可重用语句块。
—insert – 映射插入语句
—update – 映射更新语句
—delete – 映射删除语句
—select – 映射查询语句
1、增删改标签
—insert – 映射插入语句
—update – 映射更新语句
—delete – 映射删除语句
id要对应实现的方法名
<select id="getEmpById" resultType="com.achang.bean.Employee" >
select * from t_employee where id = #{id}
</select>
数据库支持主键:
dao.xml
</select>
<!--让MyBatis自动的将自增的id赋值给传入的employee对象的id属性
useGeneratedKeys属性:开启自动赋值id功能
keyProperty属性:将刚才自增的id封装给那个属性
-->
<insert id="insertEmp" useGeneratedKeys="true" keyProperty="id">
insert into t_employee(empname,gender,email)values(#{empName},#{gender},#{email})
</insert>
bean对象
public class Employee {
private Integer id;
private String empName;
private Integer gender;
private String email;
private String loginAccount;
}
**数据库没有主键:**selectKey
通过order属性设置运行顺序,keyProperty属性来设置查询后结果赋值给javabean的哪个对象
然后通过useGeneratedKeys属性设置打开获取主键,keyProperty属性设置javabean的id属性接收结果值
2、参数(Parameters)传递
1、单个参数
基本类型:
取值:#{随便写}
2、多个参数:
取值:#{参数名}是无效的的
0,1(参数索引)或者param1,param2(第几个参数paramN)
原因:
只要传入多个参数,mybatis会自动的将这些参数封装到一个map中;封装时使用的key就是参数的索引和参数的第几个标识
@param:为参数指定封装map时的key;命名参数
我们可以告诉mybatis,封装参数map的时候别乱来
3、传入map
封装多个参数为map,直接传递
4、传入bean
取值:#{bean属性名}
3、参数处理
#{}和¥{}的区别
•实际上通常被设置的是:
可能为空的列名指定 jdbcType
•#{key}:获取参数的值,预编译到SQL中。安全。
•${key}:获取参数的值,拼接到SQL中。有SQL注入问题。ORDER BY ${name}
4、查询返回List
EmployeeDao:
public interface EmployeeDao {
public List<Employee> getAllEmps();
}
dao.xml
<!--resultType:如果返回的是集合,写的是集合里面元素的类型-->
<select id="getAllEmps" resultType="com.achang.bean.Employee">
select * from t_employee
</select>
test
@Test
public void test3(){
SqlSession sqlSession = factory.openSession();
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
List<Employee> allEmps = mapper.getAllEmps();
for (Employee employee:allEmps){
System.out.println(employee);
}
5、查询返回Map
1)单条记录返回Map
dao
public interface EmployeeDao {
/****
* 列名为Key,值为value
*/
public Map<String,Object> getEmpByIdReturnMap(Integer id);
}
dao.xml
resultType属性中的map已经被mybatis自动写入别名为map了
<select id="getEmpByIdReturnMap" resultType="map">
select * from t_employee where id = #{id}
</select>
test
@Test
public void test4(){
SqlSession sqlSession = factory.openSession();
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
Map<String, Object> empByIdReturnMap = mapper.getEmpByIdReturnMap(3);
System.out.println(empByIdReturnMap);//{empname=欧尼, gender=1, id=3, login_account=b, [email protected]}
}
2)多条记录返回Map
通过@MapKey()注解来告诉mybatis数据库中哪个字段作为key主键来,封装value
dao
public interface EmployeeDao {
//key是记录的主键,value就是记录封装好的对象
//@MapKey根据数据库里面的哪个字段作为key来查询封装value
@MapKey("id")
public Map<Integer,Employee> getEmpsByIdReturnMap();
}
dao.xml
<!--查询多个的情况下,resultType属性写value封装的元素类型-->
<select id="getEmpsByIdReturnMap" resultType="com.achang.bean.Employee">
select * from t_employee
</select>
test
@Test
public void test5(){
SqlSession sqlSession = factory.openSession();
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
Map<Integer, Employee> empsByIdReturnMap = mapper.getEmpsByIdReturnMap();
System.out.println(empsByIdReturnMap);
}
6、自定义封装规则resultMap
reesultMap标签自定义封装
type属性:指定引入哪个javabaen与数据库封装对应
id属性:指定这个自定义封装的id,便于其他引用
id标签:指定主键
result标签:指定其他封装对象
property属性:指定javabean属性名
column属性:指定数据库字段名
通过resultMap属性引用那个自定义封装规则的id