Mybatis

5 篇文章 0 订阅
2 篇文章 0 订阅

Mybatis

原是Apache的一个开源项目iBatis, 2010年6月这个项目由Apache Software Foundation 迁移到了 Google Code,随着开发团队转投Google Code 旗下, iBatis3.x正式更名为MyBatis。 MyBatis 是一款优秀的持久层框架。

MyBatis 避免了几乎所有的 JDBC 代码手动设置参数以及手动获取结果集的操 作。

MyBatis 可以使用 XML 或注解来配置和映射,将数据库中的记录映射成 Java 的 POJO(Plain Old Java Objects,普通的 Java 对象),是一种 ORM(ORM Object Relational Mapping 对象关系映射)实现。

它支持动态 SQL 以及数据缓存。

Mybatis 将基本的 JDBC 常用接口封装,对外提供操作即可。

Mybatis 中文官网 https://mybatis.org/mybatis-3/zh/getting-started.html

 Mybatis 源码下载

 https://github.com/mybatis/mybatis-3/releases

MyBatis 环境搭建

1.创建一张表和表对应的实体类

2.导入 MyBatis jar 包,mysql 数据库驱动包

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>

 3.创建 MyBatis 全局配置文件

<?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">
<dataSource type="POOLED">
<property name="driver" value="" />
<property name="url" value="" />
<property name="username" value="" />
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
</configuration>

4.创建 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">
<mapper namespace="接口地址">
定义 sql 语句
</mapper>

5. 定义接口 

在接口中定义方法

public interface UserDao{ }

6.测试 MyBatis

读取配置文件

Reader reader = Resources.getResourceAsReader("mybatis-config.xml");

创建 SqlSessionFactory

SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);

创建 SqlSession

SqlSession sqlSession = sessionFactory.openSession();

获得接口代理对象

sqlSession.getMapper(接口.class);

sqlSession .close();关闭

API 接口说明

SqlSessionFactory 接口

使用 SqlSessionFactory 来创建 SqlSession,一旦创建 SqlSessionFactory 就 会在整个应用过程中始终存在。由于创建开销较大,所以没有理由去销毁再创建 它,一个应用运行中也不建议多次创建 SqlSessionFactory。

SqlSession 接口

Sqlsession 意味着创建与数据库链接会话,该接口中封装了对数据库操作的方 法,与数据库会话完成后关闭会话。 

Mybatis-Dao 层 Mapper 接口化开发

Mapper 接口开发方式只需要程序员编写 Mapper 接口,由 Mybatis 框架创建接 口的动态代理对象,使用 sqlsession.getMapper(接口.class);获得代理对象.

Mapper 接口开发需要遵循以下规范:

1、 Mapper.xml 文件中的 namespace 与 mapper 接口的类路径相同.

2、 Mapper 接口方法名和 Mapper.xml 中定义的每个 statement 的 id 相同.

3、 Mapper 接口方法的输入参数类型和 mapper.xml 中定义的每个 sql 的 parameterType 的类型相同.

4、 Mapper 接口方法的输出参数类型和 mapper.xml 中定义的每个 sql 的 resultType 的类型相同.

 

Mybatis 日志 

具体选择哪个日志实现由 MyBatis 的内置日志工厂确定。它会使用最先找到的。 Mybatis 内置的日志工厂提供日志功能,具体的日志实现有以下几种方式:

SLF4J

LOG4J

JDK_LOGGINGCOMMONS_LOGGING

STDOUT_LOGGING

配置日志

<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

 

参数传递

单个参数直接传递

User selectUsers(int id);

多个参数使用@Param(“id”)绑定

User selectUsers(@Param(“id”)int id,@Param(“name”)String name);

<select id="selectUsers" resultType="User">
select id, username, password from users where id = #{id} and username=#{name}
</select>

 传入一个复杂的对象,就需要使用 parameterType 参数进行类型定义

例如:void insertUser(User user);

<insert id="insertUser" parameterType="User">
insert into users (id, username, password)
values (#{id}, #{username}, #{password})
</insert>

 

增删改查

增加

<insert id="唯一标识" useGeneratedKeys="把新增加的主键赋值到自己定义的
keyProperty " keyProperty=“ 接收主键的属性 parameterType="参数类型">
insert into
user(userName,userAge)values(#{userName},#{userAge})
</insert>
</mapper>

 删除

<delete id="唯一标识" parameterType="参数类型">
delete from ts_user where userId = #{id}
</delete>

 修改

<update id="唯一标识" parameterType=“参数类型">
update ts_user set userName = #{userName},userAge = #{userAge}
where userId = #{userId}
</update>

查询 

<select id="唯一标识" resultType="返回结果集类型">
select * from ts_user where id= #{id}
</select>

#{} 和 ${} 区别 

#{} 占位符,是经过预编译的,编译好 SQL 语句再取值,#方式能够防止 sql 注入

      select * from t_user where uid=#{uid}

${} 拼接符,会传入参数字符串,取值以后再去编译 SQL 语句,$方式无法防止 Sql 注入 ${}

      select * from t_user where uid= '1'

注意:MyBatis 排序时使用 order by 动态参数时需要注意,用$而不是#

简而言之,#{}占位符一般用于数值传输,而${}拼接符经常用来动态的向sql传列名。

结果处理

简单类型输出映射

<select id="findUserInfoCount" resultType="int">
select count(*) from userInfo
</select>

对象映射 

如果表中的类名与类中的属性名完全相同,mybatis会自动将查询结果封装 到POJO对象中.。

mabatis会将查询到的结果自动封装到一个对象中,会自动创建给定类型的类对象
    自动封装有有条件:
    1.开启了全局的自动结果映射  autoMappingBehavior  默认是PARTIAL属性 单张表开启
    2.数据库列名与属性名相同,如果名字不一致,可以定义别名使其一致
    3.配置全局设置mapUnderscoreToCamelCase为true  即可实现数据库下划线格式与Java中驼峰格式属性名相同

如果java中使用标准驼峰命名,数据库中使用下划线连接命名,可以开始全局 设置实现自动转换

<setting name="mapUnderscoreToCamelCase" value="true"/>
<select id="findUserInfoById" parameterType="int"resultType="User">
select * from t_user where id=#{id}
</select>

好比,数据库中名叫user_name 而java中的命名习惯则会命名为userName,开启了上述设置,mybatis就会自动将此值转化并存储。

特殊处理定义 resultMap

定义 resutlMap

<resultMap id="userResultMap" type="User">
<id column="id" property="id_"/>
<result property="userName" column="user_Name_" />
<result property="userAge" column="user_age" />
</resultMap>


<select id="findUserInfoResultMap" resultMap="userResultMap">
SELECT id id_,user_name,user_age FROM t_user
</select>
<!-- 
(1). 本例的输出映射使用的是 resultMap,而非 resultType
(2). resultMap 引用了 userResultMap
-->

(1). resutlMap 的 id 属性是 resutlMap 的唯一标识,本例中定义为 “useresultMap”

(2). resutlMap 的 id 属性是映射的 POJO 类

(3). id 标签映射主键,result 标签映射非主键

(4). property 设置 POJO 的属性名称,column 映射查询结果的列名称

多表关联处理结果集

resultMap 元素中 association , collection 元素.

Collection 关联元素处理一对多关联。

比如部门和员工的关系就是一对多关系,一个部门对应好多员工。

那么在部门类中就可以创建员工集合,以便一会collection直接将值映射进部门类中。

 

 一对多关系,部门类就可以在类中创建员工集合。

多对一关系,员工类就只需要创建一个。

association

 collection

 

嵌套查询

将一个多表关联查询拆分为多次查询,先查询主表数据,然后查询关联表数据.

<association property="dept" javaType="Dept" 
select="findDeptByID" column="dept_id"></association>

(1). select:指定关联查询对象的 Mapper Statement ID 为 findDeptByID。

(2). column="dept_id":关联查询时将 dept_id 列的值传入 findDeptByID, 并将 findDeptByID 查询的结果映射到 Emp 的 dept 属性中。

(3).collection 和 association 都需要配置 select 和 column 属性,两者配置方法相同

示例代码

 <!--使用嵌套查询,吧sql分成多次查询,先查询学生信息,在查询宿舍,管理员-->
    <resultMap id="studentMap1" type="model.Student">
        <id column="id" property="id"></id>
        <result column="num" property="num"></result>
        <result column="name" property="name"></result>
        <result column="gender" property="gender"></result>
        <result column="birthday" property="birthday"></result>
        <result column="oper_time" property="operTime"></result>
        <association property="dorm" javaType="model.Dorm" column="dormid" select="findDormNum"></association>
        <association property="admin" javaType="model.Admin" column="adminid" select="findAdminAccount"></association>
    </resultMap>
    <select id="findStudentById1" resultMap="studentMap1">
        SELECT s.id,
        s.num,
        s.name,
        s.gender,
        s.birthday,
        s.dormid,
        s.adminid,
        s.oper_time
        FROM student s
        where s.id=#{id}
    </select>
    <select id="findDormNum" resultType="model.Dorm">
        SELECT num from dorm where id=#{dormid}
    </select>
    <select id="findAdminAccount" resultType="model.Admin">
        select account from admin where id=#{adminid}
    </select>

注解方式

常用注解标签

@Insert : 插入 sql , 和 xml insert sql 语法完全一样

@Select : 查询 sql, 和 xml select sql 语法完全一样

@Update : 更新 sql, 和 xml update sql 语法完全一样

@Delete : 删除 sql, 和 xml delete sql 语法完全一样

@Param : 入参

@Results : 设置结果集合

@Result : 结果

查询所有信息

@Select("select * from t_emp")
@Results(id = "empMap",value = {
@Result(column = "emp_id",property = "empId",id = true), @Result(column = "emp_name",property = "empName"), @Result(column = "emp_tel",property = "empTel"), @Result(column = "emp_education",property = "empEducation"), @Result(column = "emp_birthday",property = "empBirthday")
})
List<Employee> getAll();

查询单个信息 

@Select("select * from t_emp where emp_id=#{empId}")
@ResultMap(value="empMap")
Employee getById(@Param("empId") Integer empId);

插入信息

@Insert("insert into t_emp (emp_id, emp_name, emp_tel, " +
" emp_education, emp_birthday, fk_dept_id" +
" )" values (#{empId}, #{empName}, #{empTel}, " +
" #{empEducation}, #{empBirthday}, #{fkDeptId}" +
" )")
int insert(Employee record);

删除信息

@Delete("delete from t_emp where emp_id=#{empId}")
int deleteByPrimaryKey(@Param("empId") Integer empId);

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值