目录
2.2导入 MyBatis jar 包,mysql 数据库驱动包
一、Mybatis概述
mybatis是一款优秀的数据持久层框架,是对jdbc进行了轻量级的封装
mybatis对jdbc中的接口进行了封装,提供了一些自己的类实现。
mybatis将数据库连接配置提取到xml文件中,还将sql语句也提取到xml文件中,还可以使用注解的方式执行sql,还可以将数据库中的记录映射到java对象中(pojo),称为orm映射
Mybatis 中文官网
https://mybatis.org/mybatis-3/zh/getting-started.html
二、Mybatis配置
2.1前提
创建一个数据库,创建一个用于查询的表,创建一个Maven项目
2.2导入 MyBatis jar 包,mysql 数据库驱动包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<!-- 导入mybatis包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
2.3创键一个mybatis全局核心配置文件
注意:要在resources目录下创建mybatis.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="config.properties"></properties>
<settings>
<!-- 设置日志-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- 定义类型别名 将地址与类型对应 也可以直接定义一个包会自动寻找包下面的类型-->
<typeAliases>
<package name="com.ffyc.mybatispro.model"/>
</typeAliases>
<!-- 配置数据库信息-->
<environments default="development">
<environment id="development">
<!-- 配置事务管理器 与数据库交互的过程管理 mybatis默认是不提交sql-->
<transactionManager type="JDBC"/>
<!-- 配置数据源 type="pooled" 数据库链接技术-->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${uname}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--配置注册sql映射文件-->
<mappers>
<mapper resource="mappers/AdminMapper.xml"/>
</mappers>
</configuration>
2.4创建一个访问接口
public interface AdminDao {
//查询
Admin findAdminbyId(int id);
}
2.5创建sql映射文件
<?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">
<!--映射文件 管理员映射 namespace=为那个接口进行映射-->
<mapper namespace="com.ffyc.mybatispro.dao.AdminDao">
<!-- id-方法名 parameterType-输入数据的类型 resultType-返回值类型类的地址-->
<select id="findAdminbyId" parameterType="int" resultType="Admin">
-- sql语句部分
select * from admin where id=#{id}
</select>
</mapper>
三、测试mybatis
import com.ffyc.mybatispro.dao.AdminDao;
import com.ffyc.mybatispro.model.Admin;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class Text1 {
public static void main(String[] args) throws IOException {
//读取总配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
//创建SqlsessionFactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//获得接口代理对象
AdminDao admindao = sqlSession.getMapper(AdminDao.class);
//调用接口中的方法
Admin admin = admindao.findAdminbyId(1);
System.out.println(admin);
sqlSession.close();
}
}
执行代码就可以获取到指定id的Admin对象
四、sql映射文件
4.1参数传递
#{} 占位符,是经过预编译的,编译好 SQL 语句再取值,#方式能够防止 sql 注入
#{}:select * from admin where id=#{id}
${} 拼接符,会传入参数字符串,取值以后再去编译 SQL 语句,$方式无法防止 Sql 注入
${}:select * from admin where id= '${id}'
注意:MyBatis 排序时使用 order by 动态参数时需要注意,用$而不是#
4.2对象映射
如果表中的列名与类中的属性名完全相同,mybatis会自动将查询结果封装
到POJO对象中.
如果java中使用标准驼峰命名,数据库中使用下划线连接命名,可以开始全局设置实现自动转换
<!-- 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
4.3特殊处理映射resultMap
如果表中的列名与类中的属性名不一致,需要用到resultMap,将类的属性与表中的列名进行映射
<resultMap id="StudentMapper" type="Student">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="gender" column="gender"></result>
<result property="phone" column="phone"></result>
<association property="major" javaType="Major">
<id property="id" column="m_id"></id>
<result property="name" column="m_name" ></result>
</association>
<association property="admin" javaType="Admin">
<result property="account" column="account"></result>
</association>
</resultMap>
(1). resutlMap 的 id 属性是 resutlMap 的唯一标识,本例中定义为
“StudentMapper”
(2). resutlMap 的 id 属性是映射的 POJO 类
(3). id 标签映射主键,result 标签映射非主键
(4). property 设置 POJO 的属性名称,column 映射查询结果的列名称
使用resultMap
<select id="findStudentById" resultMap="StudentMapper">
SELECT s.id,s.name,s.gender,s.phone,m.id m_id,m.name m_name,a.account
FROM student s LEFT JOIN major m ON s.major_id=m.id
LEFT JOIN admin a ON s.admin_id=a.id WHERE s.id=#{id}
</select>
4.4多表关联处理结果集
resultMap 元素中 的association , collection 元素.
五、mybatis动态sql
MyBatis 中用于实现动态 SQL 的元素主要有:
If where trim set choose (when, otherwise) foreach
5.1where和if元素
if 标签可以对传入的条件进行判断
<where>元素会进行判断,如果它包含的标签中有返回值的话,它就插入一个 ‘where’。
此外,如果标签返回的内容是以 and或 or 开头,它会剔除掉 and或 or。
例如:
<select id="findStudent1" parameterType="Student" resultType="Student">
select * from student
<where>
<if test="gender!=null">
gender=#{gender}
</if>
<if test="name!=null">
and name=#{name}
</if>
<if test="phone!=null">
and phone=#{phone}
</if>
</where>
</select>
通过动态sql可以实现不同条件的动态查询
5.2trim元素
该标签可以实现where的功能,但是比where更加灵活,
当标签中有返回值时就在首部或尾部添加一个指定的字符,比如where.....,也可以自动覆盖掉首部或尾部的指定字符,比如and,or..........
有四个属性:
prefix="where" 前缀 prefixOverrides="and|or" 覆盖首部指定内容 suffix="" 后缀 suffixOverrides="and|or" 覆盖尾部指定内容
例如:
<select id="findStudent1" parameterType="Student" resultType="Student">
select * from student
<trim prefix="where" prefixOverrides="and|or" >
<if test="gender!=null">
gender=#{gender}
</if>
<if test="name!=null">
and name=#{name}
</if>
<if test="phone!=null">
and phone=#{phone}
</if>
</trim>
5.3choose(when,otherwise)元素
该标签类似于if(){ }else{ }if(){ }else{ } 结构
例如:
<select id="findStudent1" parameterType="Student" resultType="Student">
select * from student
<trim prefix="where" suffixOverrides="and|or">
<choose>
<when test="gender!=null">
gender=#{gender} and
</when>
<when test="name!=null">
name=#{name} and
</when>
<otherwise>
gender='男'
</otherwise>
</choose>
</trim>
</select>