MyBatis常用sql语句编写(基于MySQL数据库)

创建一张表t_user用于作示例:

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `name` varchar(20) DEFAULT NULL COMMENT '姓名',
  `sex` char(1) DEFAULT NULL COMMENT '性别:1.男 2.女 3.保密',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `del_flag` char(1) DEFAULT '0' COMMENT '删除标识:0.正常 1.删除 2.审核',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

数据库对应实体类:

package cn.com.javatest.entity;

import java.util.Date;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

/**
 * 用户实体类
 * 
 * @author  Rodge
 * @time    2018年11月9日 下午12:05:35
 * @version 1.0.0
 */
public class User {

	/**
	 * 主键ID
	 */
	private int id;
	
	/**
	 * 姓名
	 */
	private String name;
	
	/**
	 * 性别:1.男 2.女 3.保密
	 */
	private String sex;
	
	/**
	 * 生日
	 */
	private Date birthday;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
        @Override  
        public String toString() {  
            return ReflectionToStringBuilder.toString(this);  
        }
}

新增sql语句:


    INSERT INTO t_user (
	    name,
	    sex,
	    birthday
    ) VALUES (
	    #{name},
	    #{sex},
	    #{birthday}
    )

新增返回ID的sql语句(ID为整型):


      
	    SELECT LAST_INSERT_ID()
    
    INSERT INTO t_user (
	    name,
	    sex,
	    birthday
    ) VALUES (
	    #{name},
	    #{sex},
	    #{birthday}
    )

新增返回ID的sql语句(ID为字符串):


      
	    SELECT REPLACE(UPPER(UUID()), '-', '')
    
    INSERT INTO t_user (
	    name,
	    sex,
	    birthday
    ) VALUES (
	    #{name},
	    #{sex},
	    #{birthday}
    )

批量新增sql语句:


    INSERT INTO t_user (
        name,
        sex,
        birthday
    ) VALUES
    
        (#{entity.id}, 
         #{entity.sex},
         #{entity.birthday})
    

更新sql语句:


    UPDATE t_user SET
        name = #{name},
        sex = #{sex},
        birthday = #{birthday}
    WHERE del_flag = '0' AND id = #{id}	

动态更新sql语句:


    UPDATE t_user
    
        
            name = #{name},
        
        
            sex = #{sex},
        
        
            birthday = #{birthday},
        
    
    WHERE del_flag = '0' AND id = #{id}

批量更新sql语句:


    
        UPDATE t_user SET
            name = #{entity.name},
            sex = #{entity.sex},
            birthday = #{entity.birthday}
        WHERE del_flag = '0' AND id = #{entity.id}
    

删除sql语句(逻辑删除):


    UPDATE t_user SET del_flag = '1' WHERE id = #{id}

删除sql语句(物理删除):


    DELETE FROM t_user WHERE id = #{id}

批量删除sql语句:


    DELETE FROM t_user WHERE id IN
    
        #{item}
    

根据主键ID查询sql语句:

多条件动态查询sql语句:

分页查询sql语句:

根据主键ID批量查询sql语句:

多参数批量查询sql语句:

 

你可能感兴趣的:(数据库操作)