Mybatis详细版

1.简介

1.1.什么是mybatis

  • MyBatis 是一款优秀的持久层框架
  • 它支持定制化 SQL、存储过程以及高级映射。
  • MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。
  • 中文文档

1.2.持久化

为什么需要需要持久化?

  • 有一些对象,不能让他丢掉。

1.3、持久层

Dao层,Service层,Controller层….

  • 完成持久化工作的代码块
  • 层界限十分明显。

1.4 为什么需要Mybatis?

  • 帮助程序猿将数据存入到数据库中。
  • 传统的JDBC代码太复杂了。简化。框架。自动化。
  • 优点:
    • 简单易学
    • 灵活
    • sql和代码的分离,提高了可维护性。
    • 提供映射标签,支持对象与数据库的orm字段关系映射
    • 提供对象关系映射标签,支持对象关系组建维护
    • 提供xml标签,支持编写动态sql。

2、第一个Mybatis程序

思路:搭建环境–>导入Mybatis–>编写代码–>测试!

2.1.搭建环境

  1. 搭建数据库
  2. 新建一个普通的maven项目
  3. 导入maven依赖
    <dependencies>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

2.2.创建一个模块

  • 编写mybatis的核心配置文件mybatis-config.xml

连接数据库的操作和注册 mappers等一些配置类的标签

  • 找一个mybatis工具类
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static SqlSession  getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}

2.3.编写代码

  • 实体类
  • Dao接口/Mapper接口
  • 写 Dao接口/Mapper接口对应的Mapper.xml配置文件,写SQL语句

2.4.测试

  • 可能会报错,要记住在核心配置文件中注册 mappers

3.CRUD

select查询

1.编写借口

//根据ID查询用户
User getUserById(int id);

2.编写对应的mapper中的sql语句

<select id="getUserById" parameterType="int" 
resultType="com.wang.pojo.User">
        select * from mybatis.user where id = #{id}
</select>

3.测试

    @Test
    public void getUserById() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        User user = mapper.getUserById(1);
        System.out.println(user);

        sqlSession.close();
    }

Insert 添加

    <!--对象中的属性,可以直接取出来-->
    <insert id="addUser" parameterType="com.wang.pojo.User">
        insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
    </insert>

update 修改更新

    <update id="updateUser" parameterType="com.wang.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd}  where id = #{id};
    </update>

delete 删除

    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id = #{id};
    </delete>
  • 需要注意的是

增删改需要提交事务!

4.类型别名

  • 类型别名是为 Java 类型设置一个短的名字
 <!--实体类比较少的时候-->
 <typeAliases>
        <typeAlias type="com.wang.pojo.User" alias="User"/>
    </typeAliases>
<!--实体类十分多-->
<typeAliases>
    <package name="com.wang.pojo"/>
</typeAliases>

5.映射器(mappers)

注册绑定我们的Mapper文件;

  • 方式一: 【推荐使用】
<!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!-->
<mappers>
    <mapper resource="com/wang/dao/UserMapper.xml"/>
</mappers>
  • 方式二:使用class文件绑定注册
<!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!-->
<mappers>
    <mapper class="com.wang.dao.UserMapper"/>
</mappers>

注意点:

1. 接口和他的Mapper配置文件必须同名!
2. 接口和他的Mapper配置文件必须在同一个包下!
  • 方式三:使用扫描包进行注入绑定
<!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!-->
<mappers>
    <package name="com.wang.dao"/>
</mappers>

注意点:

1.接口和他的Mapper配置文件必须同名!
2.接口和他的Mapper配置文件必须在同一个包下!

6.resultMap结果集映射

可以解决字段名不一致的情况

<!--结果集映射-->
<resultMap id="UserMap" type="User">
    <!--column数据库中的字段,property实体类中的属性-->
    <result column="id" property="id"/>
    <result column="name" property="name"/>
    <result column="pwd" property="password"/>
</resultMap>

<select id="getUserById" resultMap="UserMap">
    select * from mybatis.user where id = #{id}
</select>

7.Log4j日志

6.1.先导入log4j的包
6.2.可以写一个log4j.properties配置文件来配置

8.使用注解开发

使用注解开发,只需要在对应的mapper.xml文件绑定接口即可

@Select("select * from user")
List<User> getUsers();
<!--绑定接口-->
<mappers>
    <mapper class="com.wang.dao.UserMapper"/>
</mappers>

在增删改操作时,我们需要在工具类创建的时候自动提交事务

public static SqlSession  getSqlSession(){
    return sqlSessionFactory.openSession(true);
}

关于@Param() 注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的话,可以忽略,但是建议大家都加上!
  • 我们在SQL中引用的就是我们这里的 @Param() 中设定的属性名!

9.多对一和一对多

举一个一对多的例子

//实体类
@Data
public class Student {

    private int id;
    private String name;
    private int tid;

}
@Data
public class Teacher {
    private int id;
    private String name;

    //一个老师拥有多个学生
    private List<Student> students;
}
  • 按照结果嵌套处理
   <!--按结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.name tname,t.id tid
        from student s,teacher t
        where s.tid = t.id and t.id = #{tid}
    </select>

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--复杂的属性,我们需要单独处理 对象: association 集合: collection
        javaType="" 指定属性的类型!
        集合中的泛型信息,我们使用ofType获取
        -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
  • 按照查询嵌套处理
<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id = #{tid}
</select>

<resultMap id="TeacherStudent2" type="Teacher">
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="Student">
    select * from mybatis.student where tid = #{tid}
</select>
  • 总结
  1. 关联 - association 【多对一】
  2. 集合 - collection 【一对多】
  3. javaType & ofType
    JavaType 用来指定实体类中属性的类型
    ofType 用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拧螺丝的舒克

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值