MyBatis我们这篇文章主要记录一些经常使用的操作方法。这样在开发和使用的过程中这篇文章能够当做工具书来使用。

MyBatis的数据源配置

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
</bean>
<!-- 载入myBatis-config.xml配置文件。以及扫描myBatis/文件夹下每一个DAO相应的SQL配置的XML文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:myBatis-config.xml" />
<property name="mapperLocations" value="classpath:mybatis/*.xml" />
</bean>
<!-- 将basePackage下的interface,转换为spring bean,service中能够直接 注入使用 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<property name="basePackage" value="com.test.my.dal.dao"></property>
</bean>

背景

背景:

1. 数据表,我们有一张user的数据表:

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaW5pdHBocA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="">

2. Dao的持久化对象:

public class UserPojo extends AbstractEntity {

    /**
*
*/
private static final long serialVersionUID = -4963909230377087790L; private Integer id; private String username; private String password; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} }

经常使用操作

1. myBatis-config.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>
<settings>
<!-- 是否启用 数据中 a_column 自己主动映射 到 java类中驼峰命名的属性。[默认:false] -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<typeAliases>
<!-- 映射关系 -->
<typeAlias alias="UserPojo" type="com.test.my.dal.dao.domain.UserPojo" />
</typeAliases>
<mappers></mappers>
</configuration>

2. insert操作

	<!-- 新增 -->
<insert id="addUser" parameterType="UserPojo" useGeneratedKeys="true"
keyProperty="id">
INSERT INTO
user
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
</set>
</insert>

Dao中:

void addUser(UserPojo pojo);

设置了useGeneratedKeys="true"和keyProperty="id"后,主键ID会放置到UserPojo的id属性值中。

3. update操作

	<!-- 更新一条数据 -->
<update id="updateUser" parameterType="UserPojo">
UPDATE user
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
</set>
WHERE id = #{id}
</update>

Dao中:

int updateUser(UserPojo pojo);

返回的结果为int类型,是更新的影响条数。假设更新成功。则大于0,更新失败,则为0

4. delete操作

<!-- 删除一条数据 -->
<delete id="delete" parameterType="int" >
DELETE FROM user WHERE id = #{id}
</delete>

Dao中:

    int delete(int id);

返回结果为int类型,假设删除成功。则返回影响记录数,否则返回0

5. SQL块使用

比如:

	<!-- 字段 -->
<sql id="field">
`id`,
`username`,
`password`
</sql>

使用:

<include refid="field"/>

6. SELECT使用

	<!-- 通过一个ID搜索 -->
<select id="getById" parameterType="int" resultType="UserPojo">
SELECT <include refid="field"/> FROM user WHERE id = #{id}
</select> <!-- 搜索列表 -->
<select id="getByList" parameterType="int" resultType="UserPojo">
SELECT <include refid="field"/>
FROM user ORDER BY id DESC LIMIT 10
</select>

7. if语句使用

<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>

8. where语句组装

<where>
<if test=”state != null”>
state = #{state}
</if>
<if test=”title != null”>
AND title like #{title}
</if>
<if test=”author != null and author.name != null”>
AND title like #{author.name}
</if>
</where>

9. SET语句组装

<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>

10. 条件语句

<choose>
<when test=”title != null”>
AND title like #{title}
</when>
<when test=”author != null and author.name != null”>
AND title like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>

11. foreach语句使用

WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>

当中collection能够选择list或者数组,一般使用list比較多一些。

12. @Param使用

假设Dao中有多个參数传递进来,能够使用

@Param("uids") List<Long> uids

类似于这种方式来处理。这样在XML中就能够直接使用

#{uids}

Java深入 - MyBatis的经常用法的更多相关文章

  1. 详解Java的MyBatis框架中SQL语句映射部分的编写

    这篇文章主要介绍了Java的MyBatis框架中SQL语句映射部分的编写,文中分为resultMap和增删查改实现两个部分来讲解,需要的朋友可以参考下 1.resultMap SQL 映射XML 文件 ...

  2. Java中的Socket的用法

                                   Java中的Socket的用法 Java中的Socket分为普通的Socket和NioSocket. 普通Socket的用法 Java中的 ...

  3. java String.split()函数的用法分析

    java String.split()函数的用法分析 栏目:Java基础 作者:admin 日期:2015-04-06 评论:0 点击: 3,195 次 在java.lang包中有String.spl ...

  4. Java数据库连接池封装与用法

    Java数据库连接池封装与用法 修改于抄袭版本,那货写的有点BUG,两个类,一个用法 ConnectionPool类: package com.vl.sql; import java.sql.Conn ...

  5. JAVA之关于super的用法

    JAVA之关于super的用法   路漫漫其修远兮,吾将上下而求索.——屈原<离骚> 昨天写this用法总结的时候,突然产生了一个问题,请教别人之后,有了自己的一点认识.还是把它写下来,为 ...

  6. JAVA之关于This的用法

    JAVA之关于This的用法   业精于勤,荒于嬉:行成于思,毁于随.——韩愈 用类名定义一个变量的时候,定义的应该只是一个引用,外面可以通过这个引用来访问这个类里面的属性和方法,那们类里面是够也应该 ...

  7. Java中Date各种相关用法

    Java中Date各种相关用法(一) 1.计算某一月份的最大天数 Java代码 Calendar time=Calendar.getInstance(); time.clear(); time.set ...

  8. 【转】Java 枚举7常见种用法

    原文网址:http://softbeta.iteye.com/blog/1185573 Java 枚举7常见种用法 博客分类: java java枚举enmu  原创地址:http://blog.li ...

  9. Java HashSet和LinkedHashSet的用法

    Java HashSet和LinkedHashSet的用法 类HashSet和LinkedHashSet都是接口Set的实现,两者都不能保存重复的数据.主要区别是HashSet不保证集合中元素的顺序, ...

随机推荐

  1. Js的闭包,这篇写的是比较清晰明了的

    一.变量的作用域 要理解闭包,首先必须理解Javascript特殊的变量作用域. 变量的作用域无非就是两种:全局变量和局部变量. Javascript语言的特殊之处,就在于函数内部可以直接读取全局变量 ...

  2. VUE父子组件传值问题

    一.父组件向子组件传递数据 组件实例的作用域是孤立的.这意味着不能(也不应该)在子组件的模板内直接引用父组件的数据.要让子组件使用父组件的数据,我们需要通过子组件的props选项. 1.静态props ...

  3. C#泛型集合之List

    1.命名空间:System.Collections.Generic(程序集:mscorlib)2.描述: 1).表示可通过索引访问的对象的强类型列表:提供用于对列表进行搜索.排序和操作的方法. 2). ...

  4. [转载] RED-BLACK(红黑)树的实现TreeMap源码阅读

    转载自http://lxy2330.iteye.com/blog/1664786 由于平衡二叉树与红黑树都是二叉排序树,又红黑树是对平衡二叉树的一种改进实现,所以它的很多思想算法都来源于排序二叉或平衡 ...

  5. mysql多个TimeStamp设置(转)

    原文地址:http://www.cnblogs.com/yjf512/archive/2012/11/02/2751058.html timestamp设置默认值是Default CURRENT_TI ...

  6. shell 备份脚本

    [root@izwz9hmoz58gvtu0ldpm0iz ~]# cat /usr/local/aaaa/shell_script/Mysql_Dump_LJY.sh #! /bin/bash to ...

  7. mysql主从同步+mycat读写分离+.NET程序连接mycat代理

    背景 最近新项目需要用到mysql数据库,并且由于数据量大的原因,故打算采用1主1从(主数据库负责增.删.改操作:从数据库负责查操作)的数据库架构,在实现主从之后还要实现读写分离的代理,在网上搜寻了很 ...

  8. Not found org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

    原因spring3跟spring4的jackson不一样. 解决方案: 1)spring3.x是org.springframework.http.converter.json.MappingJacks ...

  9. 用原型代替PRD时,原型应该包含哪些内容

    随着互联网节奏越来越快,传统的需求文档已经比较难适应市场的脚步,特别对于要求敏捷的团队来说,冗余而细致入微的需求文档已经成为包袱(这么长个文档领导也不会看呀).目前大多数团队更喜爱直接使用原型来代替需 ...

  10. Lucene入门-安装和运行Demo程序

    Lucene版本:7.1 一.下载安装包 https://lucene.apache.org/core/downloads.html 二.安装 把4个必备jar包和路径添加到CLASSPATH \lu ...