前言

工作这么多年,ORM框架一直选择Mybatis框架。 Mybatis的使用方式也一直在变,总体来说是越来越简单。写篇文章对各使用方式做个总结...

正文

一、Mybatis典型用法

1. 正常执行流程

♦  配置文件 - 全局配置信息和映射文件信息。全局配置信息包括:数据库配置和事务配置。映射文件就是SQL相关的

♦  Mybatis读取配置文件生成SqlSessionFactory,即回话工厂

♦  获取SqlSession, 做CRUD操作。但真正做这个事情的是底层的executor。

♦  Executor执行器把SQL分装到MappedStatement对象中。该对象包括:SQL, 输入参数映射信息和输出结果映射信息。

2. 案例

2.1 建表

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) ,
`password` varchar(20) ,
`age` int(11) ,
PRIMARY KEY (`id`)
)

2.2 全局配置文件

<?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">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3307/book"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mybatis/User.xml"/>
</mappers>
</configuration>

2.3 mapper.xml

<?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="user">
<select id="findUserById" parameterType="int" resultType="com.mybatis.User">
select * from user where id = #{id}
</select>
<select id="findUserAll" resultType="com.mybatis.User">
select * from user
</select>
<insert id="insertUser" parameterType="com.mybatis.User">
insert into user(username,password,age) values(#{username},#{password},#{age})
</insert>
<delete id="deleteUserById" parameterType="int">
delete from user where id=#{id}
</delete>
<update id="updateUserPassword" parameterType="com.mybatis.User">
update user set password=#{password} where id=#{id}
</update>
</mapper>

2.4 Dao 接口

package com.mybatis.dao;

import com.mybatis.User;

import java.util.List;

public interface UserDao {
public User findUserById(int id) throws Exception ;
public List<User> findAllUsers() throws Exception;
public void insertUser(User user) throws Exception;
public void deleteUserById(int id) throws Exception;
public void updateUserPassword(User user) throws Exception;
}

2.5 DaoImpl

package com.mybatis.dao.impl;

import com.mybatis.User;
import com.mybatis.dao.UserDao; 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;
import java.util.List; public class UserDaoImpl implements UserDao {
private static SqlSessionFactory factory = null;
static {
String resource = "mybatis/SqlMapConfig.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
factory = new SqlSessionFactoryBuilder().build(inputStream);
} public static SqlSession getSession(){
return factory.openSession();
} @Override
public User findUserById(final int id) throws Exception {
return getSession().selectOne("user.findUserById",id);
} @Override
public List<User> findAllUsers() throws Exception {
return null;
} @Override
public void insertUser(final User user) throws Exception { } @Override
public void deleteUserById(final int id) throws Exception { } @Override
public void updateUserPassword(final User user) throws Exception { }
}

2.6 User类

package com.mybatis;

import lombok.Data;

@Data
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
}

2.7 测试类

package com.mybatis.dao;

import com.mybatis.User;
import com.mybatis.dao.impl.UserDaoImpl; import org.junit.Test; public class UserDaoTest {
@Test
public void testFindUserById() throws Exception{
UserDao userDao = new UserDaoImpl();
User user = userDao.findUserById(7);
System.out.println(user);
}
}

二、Mapper代理开发方式

Mapper代理的开发方式,我们只需要编写mapper接口,不需要再Dao类,MyBatis会为我们生成代理类。代理开发方式应当遵循以下条件:

♦  mapper接口的全限定名要和mapper映射文件的namespace的值相同。

♦  mapper接口的方法名称要和mapper映射文件中的statement的id相同。

♦  mapper接口的方法参数只能有一个,且类型要和mapper映射文件中statement的parameterType的值保持一致。

♦  mapper接口的返回值类型要和mapper映射文件中statement的resultType值或resultMap中的type值保持一致。

案例:

1. 建表 同2.1

2. 全局配置 同2.2

3. mapper.xml

<?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="com.mybatis2.dao.UserDao">
<select id="findUserById" parameterType="int" resultType="com.mybatis2.User">
select * from user where id = #{id}
</select> <select id="findUserAll" resultType="com.mybatis2.User"> select * from user
</select>
<insert id="insertUser" parameterType="com.mybatis.User">
insert into user(username,password,age) values(#{username},#{password},#{age})
</insert>
<delete id="deleteUserById" parameterType="int">
delete from user where id=#{id}
</delete>
<update id="updateUserPassword" parameterType="com.mybatis.User">
update user set password=#{password} where id=#{id}
</update>
</mapper>

4.mapper类:类名无所谓,用*Dao或者*Mapper都可以

package com.mybatis2.dao;

import com.mybatis2.User;

import java.util.List;

public interface UserDao {
public User findUserById(int id) throws Exception ;
public List<User> findUserAll() throws Exception;
public void insertUser(User user) throws Exception;
public void deleteUserById(int id) throws Exception;
public void updateUserPassword(User user) throws Exception;
}

5. User类同2.5

6. 测试类

package com.mybatis.dao;

import com.mybatis2.dao.UserDao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test; import java.io.IOException;
import java.io.InputStream; public class UserDaoTest2 {
private static SqlSessionFactory factory = null;
@BeforeClass
public static void init(){
String resource = "mybatis/SqlMapConfig.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
factory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testFindUserById() throws Exception{
UserDao mapp = factory.openSession().getMapper(UserDao.class);
System.out.println(mapp.findUserById(7));
}
}

  

三、与Spring框架的集成

相关背景,使用方式官方文档已经很详细了。参考官方文档 -  http://www.mybatis.org/spring/

Mybatis 不同使用方式的更多相关文章

  1. oracle行转列、列转行、连续日期数字实现方式及mybatis下实现方式

    转载请注明出处:https://www.cnblogs.com/funnyzpc/p/9977591.html 九月份复习,十月份考试,十月底一直没法收心,赶在十一初 由于不可抗拒的原因又不得不重新找 ...

  2. SpringBoot入门教程(四)MyBatis generator 注解方式和xml方式

    MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单的 XML ...

  3. mybatis入参方式和缓冲

    1.mybatis入参方式 @Param注解参数(注解) 封装成对象入参 public int updatePassword(@Param("id")int id,@Param(& ...

  4. MyBatis简单使用方式总结

    MyBatis简单使用方式总结 三个部分来理解: 1.对MyBatis的配置部分 2.实体类与映射文件部分 3.使用部分 对MyBatis的配置部分: 1.配置用log4J显式日志 2.导入包的别名 ...

  5. MyBatis通过注解方式批量添加、修改、删除

    唯能极于情,故能极于剑 注: 本文转载于:CodeCow · 程序牛 的个人博客:http://www.codecow.cn/ 一.数据库实体DO public class User implemen ...

  6. Java Mybatis 传参方式

    一.单个参数: public List<XXBean> getXXBeanList(String xxCode); <select id="getXXXBeanList&q ...

  7. mybatis之注解方式实现

    * 使用mybatis举例,使用注解方式实现* 不需要针对UserMapperI接口去编写具体的实现类代码,这个具体的实现类由MyBatis帮我们动态构建出来,我们只需要直接拿来使用即可.* 1.导入 ...

  8. 关于整合spring+mybatis 第二种方式

    和第一种方式一样的步骤,不过bean.xml中有些许差异 <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory& ...

  9. mybatis通过插件方式实现读写分离

    原理:通过自定义mybatis插件,拦截Executor的update和query方法,检查sql中有select就用读的库,其它的用写的库(如果有调用存储过程就另当别论了) @Intercepts( ...

随机推荐

  1. 11G新特性 -- 收缩临时表空间

    当大任务执行完毕,并不会立即释放临时表空间.有时候通过删除然后重建临时表空间的速度可能更快.不过对于在线系统可能不会那么容易删除重建,所以11g中可以在线收缩临时表空间或单个临时数据文件. 收缩临时表 ...

  2. goland激活码

    http://idea.youbbs.org      

  3. pandas DataFrame applymap()函数

    pandas DataFrame的 applymap() 函数可以对DataFrame里的每个值进行处理,然后返回一个新的DataFrame: import pandas as pd df = pd. ...

  4. [转]bootstrap table 动态列数

    原文地址:https://my.oschina.net/u/2356355/blog/1595563 据说bootstrap table非常好用,从入门教程中了解到它的以下主要功能: 由于固定表头意味 ...

  5. hdoj:2045

    #include <iostream> using namespace std; ]; int main() { int n; a[] = ; a[] = ; a[] = ; ; i &l ...

  6. 深夜一次数据库执行SQL思考(怎么看执行报错信息)

    如下sql在执行时 DROP TABLE IF EXISTS `book`; CREATE TABLE `book` ( `id` int(11) NOT NULL AUTO_INCREMENT, ` ...

  7. unable to locate package gparted

    在unbuntu安装gparted的时候出现这个错误提示,意思为:找不到这个安装包 可能的原因: 1.当前系统更新包没有更新,执行命令:sudo apt-get update 2.命令错误,重新检查需 ...

  8. Java知多少(49)throw:异常的抛出

    到目前为止,你只是获取了被Java运行时系统抛出的异常.然而,程序可以用throw语句抛出明确的异常.Throw语句的通常形式如下:    throw ThrowableInstance;这里,Thr ...

  9. ThinkingInJava 学习 之 0000005 访问权限控制

    1. 包:库单元 1. 代码组织 2. 创建独一无二的包名 3. 定制工具库 4. 用import改变行为 5. 对使用包的忠告 2. Java访问权限修饰词 1. 包访问权限 2. public : ...

  10. windows系统下,express构建的node项目中,如何用debug控制调试日志

    debug是一款控制日志输出的库,可以在开发调试环境下打开日志输出,生产环境下关闭日志输出.这样比console.log方便多了,console.log只有注释掉才能不输出. debug库还可以根据d ...