一.别名配置
1.修改mybatis-config.xml文件
方法一:直接给某一个类起别名:
<typeAlias type="com.bigfong.mybatis.hello.User" alias="User"/>
方法二:给一个包(包含子包)中所有类起别名
<package name="com.bigfong.mybatis.hello" />
方法三:使用@Alias注解设置类的别名
2.mapper的xml文件
<select id="get" resultType="User">
select id,name,salary from t_user where id = #{id}
</select>
resultType不需全限名
系统自带别名
以下是常见的Java类型内建的相应的类型别名,它们都是大小写不敏感的,需要注意的是由基本类型名称重复导致的特殊处理
二.属性配置处理
添加db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisdemo
jdbc.username=root
jdbc.password=123456
jdbc.initialSize=2
全局配置文件
<!-- 从classpath的根路径加载属性 -->
<properties resource="db.properties"/>
<!-- 1.配置数据库环境 -->
<environments default="dev">
<!-- 开发环境:在以后事务管理器和连接池都是交给spring框架来管理的 -->
<environment id="dev">
<!-- [1]事务管理器 -->
<transactionManager type="JDBC" />
<!-- [2]数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
三.结果集映射
解决“当数据表列名和对象的属性名不对应时的问题
<resultMap id="BaseResultMap" type="User" >
<!-- 功能和result一样,如果是主键建议使用id元素,提升性能 -->
<id column="u_id" property="id"/>
<!-- 匹配 对象中的哪一个属性对应表中的哪一个列-->
<result column="u_name" property="name"/>
<result column="u_salary" property="salary"/>
</resultMap>
<select id="listAll" resultMap="BaseResultMap">
select id,name,salary from t_user
</select>
resultMap元素定义了一个ORM的具体映射规则
type属性:最终返回的对象类型
id:该结果映射名称,这个名称就是在get或listAll中使用的resultMap对应的ID
子元素result:把结果集中的哪一个列设置到对象中的哪一个属性上,处理变通列
子元素id:和result功能相同,处理主键时使用id元素提升性能,处理主键列
四.Mapper组件
使用namespace.id的方式去找到SQL元素的方式有几个问题:
1.namespace.id使用的是String类型,一旦编写错误,只有等到运行代码才能报错
2.传入的实际参数类型不能被检查
3.每个操作的代码模板类似
Mapper接口
使用Mapper组件
1.创建一个Mapper接口(类似DAO接口),接口要求
1)这个接口的全限定名称---对应的Mapper文件的namespace;
2)这个接口中的方法和Mapper文件中的Sql元素一一对应
[1].方法名字对应SQL元素的id;
[2]方法的参数类型对应SQL元素中定义的paramterType类型(一般不写)
[3]方法的返回类型对应SQL元素中定义的resultType/resultMap类型;
2.创建SqlSession
3.通过SqlSession.getMapper(XxxMapper.class)方法得到一个Mapper对象
4.调用Mapper对象上的方法完成对象的CRUD;
UserMapper接口
public interface UserMapper {
void save(User u);
void update(User u);
void delete(Long id);
User get(Long id);
List<User> listAll();
}
UserMapper.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.bigfong.mybatis.mapintf.domain.mapper.UserMapper">
<!-- 添加 -->
<insert id="save" useGeneratedKeys="true" keyProperty="id" >
insert into t_user (name,salary) values (#{name},#{salary})
</insert>
<!-- 更新 -->
<update id="update" >
update t_user set name = #{name},salary = #{salary} where id = #{id}
</update>
<!-- 删除 -->
<delete id="delete">
delete from t_user where id = #{id}
</delete>
<select id="get" resultType="User">
select id,name,salary from t_user where id = #{id}
</select>
<select id="listAll" resultType="User">
select id,name,salary from t_user
</select>
</mapper>
测试代码
// 查询单个
//Mapper接口的原理:动态代理,代理对像为com.sun.proxy.$Proxy9
@Test
void testGet() throws Exception {
SqlSession session = MybatisUtil.getSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
System.out.println(userMapper.getClass());
User user = userMapper.get(1L);
session.close();
System.out.println(user);
}
// 查询所有
@Test
void testListAll() throws Exception {
SqlSession session = MybatisUtil.getSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
List<User> list = userMapper.listAll();
session.close();
System.out.println(list);
}
Mapper接口的原理:动态代理
五.参数处理
1.封装POJO和Map
如果在Mybatis中传入多个参数,此时可以把参数封装到POJO对象或Map中,在Mapper文件的SQL中#{}里面引用的就是对象属性或Map里面的key.
MyBatis在#{}中参数流程:
1)会去POJO对象中,按照属性名或者Map的Key去查询
2)如果找不到,尝试直接把方法的实际参数作为查询参数值
2.Param注解
如果要在Mapper接口上的一个方法中添加多个参数,此时一定要在每个参数前使用@Param标签。
原理:MyBatis底层自动把这些参数包装成一个Map对象,@Param中的value就会作为这个Map的key,对应的参数值,就会作为这个Key的value
Mapper接口
User login(@Param("username") String username,@Param("password") String password);
Mapper文件
<select id="login">
select id,username,password from t_user
where username=#{username} and password=#{password}
</select>
3.集合/数组
当传递一个List对象或数组对象参数给MyBatis时,MyBatis会自动把它包装到一个Map中,此时List对象会以list作为key,数组对象会以array作为key,也可以使用Param注解设置key名
六.使用注解开发
public interface UserMapper {
/*
<insert id="save" useGeneratedKeys="true" keyProperty="id" >
insert into t_user (name,salary) values (#{name},#{salary})
</insert>
*/
@Insert("insert into t_user (name,salary) values (#{name},#{salary})")
@Options(useGeneratedKeys=true,keyProperty="id")
void save(User u);
/*
<update id="update" >
update t_user set name = #{name},salary = #{salary} where id = #{id}
</update>
*/
@Update("update t_user set name = #{name},salary = #{salary} where id = #{id}")
void update(User u);
/*
<delete id="delete">
delete from t_user where id = #{id}
</delete>
*/
@Delete("delete from t_user where id = #{id}")
void delete(Long id);
/*
<select id="get" resultType="User">
select id,name,salary from t_user where id = #{id}
</select>
*/
@Select("select id as u_id,name as u_name,salary as u_salary from t_user where id = #{id}")
@Results(id="BaseResultMap",value= {
@Result(column="u_id",property="id"),
@Result(column="u_name",property="name"),
@Result(column="u_salary",property="salary"),
})
User get(Long id);
/*
<select id="listAll" resultType="User">
select id,name,salary from t_user
</select>
*/
@Select("select id,name,salary from t_user")
@ResultType(User.class)
List<User> listAll();
}
七.其他
1.#和$
1).通过#和$都可以获取对象中的属性
2).区别:
[1].使用#传递的参数会先转换为占位符,无论传递是什么类型数据都会带一个单引号
[2]使用$传递的参数,直接把值作为SQL语句的一部分
使用$容易导致SQL注入问题----->使用#更安全
但是在做排序的时候,不能使用带引号的数据
结论
如果需要设置占位符参数全部使用#,也就是SQL中可以使用?的地方
如果需要拼接成SQL的一部分使用$,比如排序
上一篇: MyBatis3.x整理:(一)MyBatis基础
下一篇: MyBatis3.x整理:(三)动态SQL