MyBatis框架的使用及源码分析(一) 配置与使用
我们先来看一个例子,简单的了解一下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框架的使用及源码分析(一) 配置与使用的更多相关文章
- MyBatis框架的使用及源码分析(二) 配置篇 SqlSessionFactoryBuilder,XMLConfigBuilder
在 <MyBatis框架中Mapper映射配置的使用及原理解析(一) 配置与使用> 的demo中看到了SessionFactory的创建过程: SqlSessionFactory sess ...
- MyBatis框架的使用及源码分析(三) 配置篇 Configuration
从上文<MyBatis框架中Mapper映射配置的使用及原理解析(二) 配置篇 SqlSessionFactoryBuilder,XMLConfigBuilder> 我们知道XMLConf ...
- MyBatis框架的使用及源码分析(十一) StatementHandler
我们回忆一下<MyBatis框架的使用及源码分析(十) CacheExecutor,SimpleExecutor,BatchExecutor ,ReuseExecutor> , 这4个Ex ...
- MyBatis框架的使用及源码分析(九) Executor
从<MyBatis框架的使用及源码分析(八) MapperMethod>文中我们知道执行Mapper的每一个接口方法,最后调用的是MapperMethod.execute方法.而当执行Ma ...
- MyBatis框架的使用及源码分析(八) MapperMethod
从 <MyBatis框架中Mapper映射配置的使用及原理解析(七) MapperProxy,MapperProxyFactory> 文中,我们知道Mapper,通过MapperProxy ...
- MyBatis框架的使用及源码分析(六) MapperRegistry
我们先Mapper接口的调用方式,见<MyBatis框架中Mapper映射配置的使用及原理解析(一) 配置与使用>的示例: public void findUserById() { Sql ...
- MyBatis框架的使用及源码分析(五) DefaultSqlSessionFactory和DefaultSqlSession
我们回顾<MyBatis框架中Mapper映射配置的使用及原理解析(一) 配置与使用> 一文的示例 private static SqlSessionFactory getSessionF ...
- MyBatis框架的使用及源码分析(四) 解析Mapper接口映射xml文件
在<MyBatis框架中Mapper映射配置的使用及原理解析(二) 配置篇 SqlSessionFactoryBuilder,XMLConfigBuilder> 一文中,我们知道mybat ...
- MyBatis框架的使用及源码分析(十) CacheExecutor,SimpleExecutor,BatchExecutor ,ReuseExecutor
Executor分成两大类,一类是CacheExecutor,另一类是普通Executor. 普通类又分为: ExecutorType.SIMPLE: 这个执行器类型不做特殊的事情.它为每个语句的执行 ...
随机推荐
- python学习第一天-语法学习
1.python简介 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,Guido开始写能够解释Python语言语法的解释器.Python这个名字,来自 ...
- 不同品牌交换机设置telnet方法
H3C交换机:1.设置telnet system-view super password level 3 cipher ******telnet server enable user-interfac ...
- oracle怎样查询索引的使用情况
查询用户的索引select index_name,table_name,tablespace_name, index_type,uniqueness , status from dba_indexes ...
- 特殊符号存入mysql数据库时报错:Incorrect string value: '\xF0\x9F\x98\x84\xF0\x9F的解决方法
问题描述:从新浪微博抓取消息保存到MySQL数据中,对应数据库字段为varchar,字符编码utf-8.部分插入成功,部分插入失败,报错如标题. 在网上查询,有人说是编码问题,建议修改编码格式,比如改 ...
- Maven 生命周期 和插件
1.3 生命周期1.3.1 什么是生命周期? Maven生命周期就是为了对所有的构建过程进行抽象和统一.包括项目清理.初始化.编译.打包.测试.部署等几乎所有构建步骤. 生命周期可以理解为构建工程的步 ...
- 第49天:封装自己的scrollTop
一.scroll家族 offset 自己的偏移scroll滚动的 scrollTop和scrollLeftscrollTop 被卷去的头部当滑动滚轮浏览网页的时候,网页隐藏在屏幕上方的距离二.页面滚动 ...
- Oracle数据库中心双活之道:ASM vs VPLEX
Oracle数据库中心双活之道:ASM vs VPLEX 来源 https://www.cnblogs.com/wenjiewang/p/7460212.html 双活方案对比:ASM vs V-PL ...
- (转)Ubuntu 12.04 LTS安装VMware Tools实现linux和window 互相复制:无法找到kernel header path的问题
Ubuntu 12.04 LTS安装VMware Tools无法找到kernel header path的问题 ubuntuvmware Ubuntu 12.04 安装 VMware Tools, ...
- BZOJ4004:[JLOI2015]装备购买——题解
https://www.lydsy.com/JudgeOnline/problem.php?id=4004 https://www.luogu.org/problemnew/show/P3265 脸哥 ...
- Static全局变量与普通的全局变量有什么区别?static函数与普通函数有什么区别?
Static全局变量与普通的全局变量有什么区别? 答: 全局变量(外部变量)的说明之前再冠以static就构成了静态的全局变量.全局变量本身就是静态存储方式,静态全局变量当然也是静态存储方式. 这两者 ...