我们先来看一个例子,简单的了解一下mybatis的mapper接口方式的使用。

 package org.mybatis.spring.sample;

 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 org.junit.Test;
import org.mybatis.spring.sample.bean.User;
import org.mybatis.spring.sample.mapper.UserMapper; import java.io.IOException; public class MybatisTest { /**
* 读取mybatis的配置文件,生成SqlSessionFactory
*
* @return
*/
private static SqlSessionFactory getSessionFactory() {
SqlSessionFactory sessionFactory = null;
String resource = "mybatisConfig.xml";
try {
sessionFactory = new SqlSessionFactoryBuilder().build(Resources
.getResourceAsReader(resource));
} catch (IOException e) {
e.printStackTrace();
}
return sessionFactory;
} @Test
public void findUserById() {
SqlSessionFactory sqlSessionFactory = getSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectByPrimaryKey(1l);
System.out.println(user.getId() + " / " + user.getName());
} }

输出结果

1 /  赵大

数据库表 user

User.java

 /*
* User.java
* Copyright(C) 2015-2017 Jstudio.org
* All rights reserved.
* --------------------------------------
* 2017-09-17 Created.
*/
package org.mybatis.spring.sample.bean; import java.io.Serializable; /**
*
* This class was generated by MyBatis Generator.
* This class corresponds to the database table user
*
* @mbg.generated do_not_delete_during_merge 2017-09-17
*/
public class User implements Serializable {
/**
* 主键
*/
private Long id; /**
* 用户名
*/
private String name; /**
* 密码
*/
private String password; /**
* 电子邮件
*/
private String email; /**
* 年龄
*/
private Integer age; private static final long serialVersionUID = 1L; /**
* 获取主键
*
* @return id - 主键
*/
public Long getId() {
return id;
} /**
* 设置主键
*
* @param id 主键
*/
public void setId(Long id) {
this.id = id;
} /**
* 获取用户名
*
* @return name - 用户名
*/
public String getName() {
return name;
} /**
* 设置用户名
*
* @param name 用户名
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
} /**
* 获取密码
*
* @return password - 密码
*/
public String getPassword() {
return password;
} /**
* 设置密码
*
* @param password 密码
*/
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
} /**
* 获取电子邮件
*
* @return email - 电子邮件
*/
public String getEmail() {
return email;
} /**
* 设置电子邮件
*
* @param email 电子邮件
*/
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
} /**
* 获取年龄
*
* @return age - 年龄
*/
public Integer getAge() {
return age;
} /**
* 设置年龄
*
* @param age 年龄
*/
public void setAge(Integer age) {
this.age = age;
}
}

UserMapper.java

 /*
* UserMapper.java
* Copyright(C) 2015-2017 Jstudio.org
* All rights reserved.
* --------------------------------------
* 2017-09-17 Created.
*/
package org.mybatis.spring.sample.mapper; import org.mybatis.spring.sample.bean.User; import java.util.List; public interface UserMapper { int insert(User entity); int insertSelective(User entity); int deleteByPrimaryKey(Long id); int updateByPrimaryKeySelective(User entity); int updateByPrimaryKey(User entity); User selectByPrimaryKey(Long id); }

UserMapper.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="org.mybatis.spring.sample.mapper.UserMapper">
<!-- This is automatically generated by MyBatis Generator on 2017-09-17. -->
<resultMap id="BaseResultMap" type="org.mybatis.spring.sample.bean.User">
<!-- WARNING - This element is automatically generated by MyBatis Generator, modify carefully. -->
<id column="id" jdbcType="BIGINT" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="age" jdbcType="INTEGER" property="age" />
</resultMap>
<sql id="Base_Column_List">
<!-- WARNING - This element is automatically generated by MyBatis Generator, modify carefully. -->
id, name, password, email, age
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
<!-- WARNING - This element is automatically generated by MyBatis Generator, modify carefully. -->
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
<!-- WARNING - This element is automatically generated by MyBatis Generator, modify carefully. -->
delete from user
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="org.mybatis.spring.sample.bean.User">
<!-- WARNING - This element is automatically generated by MyBatis Generator, modify carefully. -->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user (name, password, email,
age)
values (#{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="org.mybatis.spring.sample.bean.User">
<!-- WARNING - This element is automatically generated by MyBatis Generator, modify carefully. -->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
SELECT LAST_INSERT_ID()
</selectKey>
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
name,
</if>
<if test="password != null">
password,
</if>
<if test="email != null">
email,
</if>
<if test="age != null">
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="email != null">
#{email,jdbcType=VARCHAR},
</if>
<if test="age != null">
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="org.mybatis.spring.sample.bean.User">
<!-- WARNING - This element is automatically generated by MyBatis Generator, modify carefully. -->
update user
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="email != null">
email = #{email,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="org.mybatis.spring.sample.bean.User">
<!-- WARNING - This element is automatically generated by MyBatis Generator, modify carefully. -->
update user
set name = #{name,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>

mybatisConfig.xml

<?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://127.0.0.1:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="sqlmapping/UserMapper.xml"/>
</mappers>
</configuration>

后继我们将继续讲解Mybatis如何加载配置,解析Mappper的xml,创建和使用Mapper。

MyBatis框架的使用及源码分析(一) 配置与使用的更多相关文章

  1. MyBatis框架的使用及源码分析(二) 配置篇 SqlSessionFactoryBuilder,XMLConfigBuilder

    在 <MyBatis框架中Mapper映射配置的使用及原理解析(一) 配置与使用> 的demo中看到了SessionFactory的创建过程: SqlSessionFactory sess ...

  2. MyBatis框架的使用及源码分析(三) 配置篇 Configuration

    从上文<MyBatis框架中Mapper映射配置的使用及原理解析(二) 配置篇 SqlSessionFactoryBuilder,XMLConfigBuilder> 我们知道XMLConf ...

  3. MyBatis框架的使用及源码分析(十一) StatementHandler

    我们回忆一下<MyBatis框架的使用及源码分析(十) CacheExecutor,SimpleExecutor,BatchExecutor ,ReuseExecutor> , 这4个Ex ...

  4. MyBatis框架的使用及源码分析(九) Executor

    从<MyBatis框架的使用及源码分析(八) MapperMethod>文中我们知道执行Mapper的每一个接口方法,最后调用的是MapperMethod.execute方法.而当执行Ma ...

  5. MyBatis框架的使用及源码分析(八) MapperMethod

    从 <MyBatis框架中Mapper映射配置的使用及原理解析(七) MapperProxy,MapperProxyFactory> 文中,我们知道Mapper,通过MapperProxy ...

  6. MyBatis框架的使用及源码分析(六) MapperRegistry

    我们先Mapper接口的调用方式,见<MyBatis框架中Mapper映射配置的使用及原理解析(一) 配置与使用>的示例: public void findUserById() { Sql ...

  7. MyBatis框架的使用及源码分析(五) DefaultSqlSessionFactory和DefaultSqlSession

    我们回顾<MyBatis框架中Mapper映射配置的使用及原理解析(一) 配置与使用> 一文的示例 private static SqlSessionFactory getSessionF ...

  8. MyBatis框架的使用及源码分析(四) 解析Mapper接口映射xml文件

    在<MyBatis框架中Mapper映射配置的使用及原理解析(二) 配置篇 SqlSessionFactoryBuilder,XMLConfigBuilder> 一文中,我们知道mybat ...

  9. MyBatis框架的使用及源码分析(十) CacheExecutor,SimpleExecutor,BatchExecutor ,ReuseExecutor

    Executor分成两大类,一类是CacheExecutor,另一类是普通Executor. 普通类又分为: ExecutorType.SIMPLE: 这个执行器类型不做特殊的事情.它为每个语句的执行 ...

随机推荐

  1. vue.js 创建组件 子父通信 父子通信 非父子通信

    1.创建组件 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...

  2. 如何用vs查看框架函数管道模型

    调试状态下 函数调用的 代码图,我们可以看到MVC框架的函数管道模型 源文章标题: 源文章:https://www.cnblogs.com/1996V/p/9037603.html 扩展阅读:http ...

  3. js设计模式之代理模式以及订阅发布模式

    为啥将两种模式放在一起呢?因为这样文章比较长啊. 写博客的目的我觉得首要目的是整理自己的知识点,进而优化个人所得知识体系.知识成为个人的知识,就在于能够用自己的话表达同一种意义. 本文是设计模式系列文 ...

  4. 编译android6.0错误recipe for target 'out/host/linux-x86/obj/lib/libart.so' failed

    转自:http://blog.csdn.net/ztguang/article/details/52856076 trip: libpagemap_32 (out/target/product/xx/ ...

  5. [Redis]在.NET平台下的具体应用

    一.安装第三方驱动 PM> Install-Package ServiceStack.Redis 二.使用C#语言调用类库访问Redis

  6. [C/C++] C++类对象创建问题

    CSomething a();// 没有创建对象,这里不是使用默认构造函数,而是定义了一个函数,在C++ Primer393页中有说明. CSomething b(2);//使用一个参数的构造函数,创 ...

  7. 【bzoj3732】Network 最小生成树+倍增LCA

    题目描述 给你N个点的无向图 (1 <= N <= 15,000),记为:1…N. 图中有M条边 (1 <= M <= 30,000) ,第j条边的长度为: d_j ( 1 & ...

  8. linux虚拟机磁盘扩展与分区大小调整

    有段时间觉得linux虚拟机上的磁盘不太够用,研究了下其磁盘扩展 1.linux虚拟机磁盘扩展 step1. 先关机在编辑虚拟机中,找到硬盘选项增加空间,进行扩展step2. 进入root fdisk ...

  9. CSS-posiziton

    1. 想要实现,”返回顶部”永远位于页面的右下角.需要用到position函数.CSS:层叠样式表.用到了分层的功能. position:fixed;  永远固定在一个地方. <!DOCTYPE ...

  10. 【题解】Atcoder ARC#83 E-Bichrome Tree

    哈哈~自己做出来的E题!(虽然这题被机房大佬强D极水).最开始神经错乱,写了个完全不对的贪心,竟然只错了4个点(。•ˇ‸ˇ•。) 可以发现,一个节点的子树内部和他颜色相同的节点权值和 是固定的,那么不 ...