mybatis进阶

本文详细介绍了Mybatis的Dao层实现,包括传统开发方式和代理方式,并探讨了动态SQL的使用,如<if>、<where>、<foreach>标签以及SQL片段抽取。此外,还讲解了一对一、一对多和多对多的多表查询实现,通过<resultMap>配置映射关系。
摘要由CSDN通过智能技术生成

1.Mybatis的Dao层实现

1.1 传统开发方式

1.1.1编写UserDao接口

public interface UserDao {

List<User> findAll() throws IOException;

}

1.1.2.编写UserDaoImpl实现

public class UserDaoImpl implements UserDao {

public List<User> findAll() throws IOException {

InputStream resourceAsStream =

Resources.getResourceAsStream("SqlMapConfig.xml");

SqlSessionFactory sqlSessionFactory = new

SqlSessionFactoryBuilder().build(resourceAsStream);

SqlSession sqlSession = sqlSessionFactory.openSession();

List<User> userList = sqlSession.selectList("userMapper.findAll");

sqlSession.close();

return userList;

}

}

1.1.3 测试传统方式

@Test

public void testTraditionDao() throws IOException {

UserDao userDao = new UserDaoImpl();

List<User> all = userDao.findAll();

System.out.println(all);

}

1.2 代理开发方式

1.2.1 代理开发方式介绍

采用 Mybatis 的代理开发方式实现 DAO 层的开发,这种方式是我们后面进入企业的主流。

Mapper 接口开发方法只需要程序员编写Mapper 接口(相当于Dao 接口),由Mybatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

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

1) Mapper.xml文件中的namespace与mapper接口的全限定名相同

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

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

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

1.2.2 编写UserMapper接口

1.2.3测试代理方式

@Test

public void testProxyDao() throws IOException {

InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");

SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

SqlSession sqlSession = sqlSessionFactory.openSession();

//获得MyBatis框架生成的UserMapper接口的实现类

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

User user = userMapper.findById(1);

System.out.println(user);

sqlSession.close();

}

1.3 知识小结

MyBatis的Dao层实现的两种方式:

手动对Dao进行实现:

传统开发方式

代理方式对Dao进行实现:

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

 

2. 动态sql

动态sql语句概述

Mybatis 的映射文件中,前面我们的 SQL 都是比较简单的,有些时候业务逻辑复杂时,我们的 SQL是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了。

     动态sql:sql语句是在程序运行期间动态生成的

    静态sql:sql语句是预先编写好的

 

<if>标签:

我们根据实体类的不同取值,使用不同的 SQL语句来进行查询。比如在 id如果不为空时可以根据id查询,如果username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到。

    语法:

        <if test="条件表达式">

            sql语句信息

        </if>

 

<select id="findByCondition" parameterType="user" resultType="user">

    select * from User

    <where>

        <if test="id!=0">

            and id=#{id}

        </if>

        <if test="username!=null">

            and username=#{username}

        </if>

    </where>

</select>

    

<where>标签

    1. 如果第一个成立的条件前的关键字不是where,会自动修改成where

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值