一、概述

MyBatis的基本概念与产生背景已经在上一篇文章中介绍过,本篇将完成如下几步,实现MyBatis的快速使用:

(1)实体类的创建

(2)导入MyBatis依赖

(3)编写MyBatis核心配置文件

(4)SQL映射文件:实现了SQL与Java代码的分离

(5)Java代码使用框架

二、快速使用

(1)引入MySQL驱动、MyBatis依赖

mysqlmysql-connector-java8.0.25org.mybatismybatis3.5.12

(2)添加mybatis-config.xml配置文件(来源),注意填写自己的数据源相关信息

(3)mapper的Java文件与xml文件分别如下:

package com.byhuang.mapper;import com.byhuang.entity.User;public interface UserMapper {User selectUser(long id);}
select * from user where id = #{id}

(4)测试类:注意以下实现有两种方式

package com.byhuang.test;import com.byhuang.entity.User;import com.byhuang.mapper.UserMapper;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 Test {public static void main(String[] args) throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// old version: 不需要定义mapper接口,直接引用xmltry (SqlSession session = sqlSessionFactory.openSession()) {User user = (User) session.selectOne("com.byhuang.mapper.UserMapper.selectUser", 2);System.out.println(user);}// new version: 定义mapper接口,接口名与xml中sql id一致try (SqlSession session = sqlSessionFactory.openSession()) {UserMapper mapper = session.getMapper(UserMapper.class);User user = mapper.selectUser(1L);System.out.println(user);}}}
三、条件查询

条件查询的三种情况如下:

* (1)散装参数:需要使用@Param* (2)实体类参数:只需要SQL中的参数名和实体类属性名对应上,不需要@Param注解* (3)map集合:map的键与参数名对应上,不需要@Param注解

示例:

UserMapper mapper = session.getMapper(UserMapper.class);Map map = new HashMap();map.put("id", 2L);map.put("name", "ls");map.put("phone", "777");User user1 = mapper.selectUser1(1L, "zs", "888");User user2 = mapper.selectUser2(new User(1L, "zs", "888"));User user3 = mapper.selectUser3(map);System.out.println("======参数=======");System.out.println(user1);System.out.println(user2);System.out.println(user3);
User selectUser1(@Param("id") long id, @Param("name") String name, @Param("phone") String phone);User selectUser2(User user);User selectUser3(Map map);
select * from user where id = #{id} and name = #{name} and phone = #{phone};select * from user where id = #{id} and name = #{name} and phone = #{phone};select * from user where id = #{id} and name = #{name} and phone = #{phone};

以上便是MyBatis的快速使用。