https://github.com/mybatis/mybatis-dynamic-sql

MyBatis Dynamic SQL

   

What Is This?

This library is a framework for generating dynamic SQL statements. Think of it as a typesafe SQL templating library, with additional support for MyBatis3 and Spring JDBC Templates.

The library will generate full DELETE, INSERT, SELECT, and UPDATE statements formatted for use by MyBatis or Spring. The most common use case is to generate statements, and a matching set of parameters, that can be directly used by MyBatis. The library will also generate statements and parameter objects that are compatible with Spring JDBC templates.

The library works by implementing an SQL-like DSL that creates an object containing a full SQL statement and any parameters required for that statement. The SQL statement object can be used directly by MyBatis as a parameter to a mapper method.

The library will generate these types of SQL statements:

  • DELETE statements with flexible WHERE clauses
  • INSERT statements of several types:
    • A statement that inserts a single record and will insert null values into columns (a "full" insert)
    • A statement that inserts a single record that will ignore null input values and their associated columns (a "selective" insert)
    • A statement that inserts into a table using the results of a SELECT statement
    • A parameter object is designed for inserting multiple objects with a JDBC batch
  • SELECT statements with a flexible column list, a flexible WHERE clause, and support for distinct, "group by", joins, unions, "order by", etc.
  • UPDATE statements with a flexible WHERE clause. Like the INSERT statement, there are two varieties of UPDATE statements:
    • A "full" update that will set null values
    • A "selective" update that will ignore null input values

The primary goals of the library are:

  1. Typesafe - to the extent possible, the library will ensure that parameter types match the database column types
  2. Expressive - statements are built in a way that clearly communicates their meaning (thanks to Hamcrest for some inspiration)
  3. Flexible - where clauses can be built using any combination of and, or, and nested conditions
  4. Extensible - the library will render statements for MyBatis3, Spring JDBC templates or plain JDBC. It can be extended to generate clauses for other frameworks as well. Custom where conditions can be added easily if none of the built in conditions are sufficient for your needs.
  5. Small - the library is a small dependency to add. It has no transitive dependencies.

This library grew out of a desire to create a utility that could be used to improve the code generated by MyBatis Generator, but the library can be used on it's own with very little setup required.

Requirements

The library has no dependencies. Java 8 or higher is required.

Show Me an Example

One capability is that very expressive dynamic queries can be generated. Here's an example of what's possible:

    @Test
public void testComplexCondition() {
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
AnimalDataMapper mapper = sqlSession.getMapper(AnimalDataMapper.class); SelectStatementProvider selectStatement = select(id, animalName, bodyWeight, brainWeight)
.from(animalData)
.where(id, isIn(1, 5, 7))
.or(id, isIn(2, 6, 8), and(animalName, isLike("%bat")))
.or(id, isGreaterThan(60))
.and(bodyWeight, isBetween(1.0).and(3.0))
.orderBy(id.descending(), bodyWeight)
.build()
.render(RenderingStrategy.MYBATIS3); List<AnimalData> animals = mapper.selectMany(selectStatement);
assertThat(animals.size()).isEqualTo(4);
} finally {
sqlSession.close();
}
}

How Do I Use It?

The following discussion will walk through an example of using the library to generate a dynamic SELECT or DELETE statement. The full source code for this example is in src/test/java/examples/simple in this repo.

The database table used in the example is defined as follows:

create table SimpleTable (
id int not null,
first_name varchar(30) not null,
last_name varchar(30) not null,
birth_date date not null,
employed varchar(3) not null,
occupation varchar(30) null,
primary key(id)
);

First - Define database table and columns

The class org.mybatis.dynamic.sql.SqlTable is used to define a table. A table definition includes the actual name of the table (including schema or catalog if appropriate). A table alias can be applied in a select statement if desired. Your table should be defined by extending the SqlTable class.

The class org.mybatis.dynamic.sql.SqlColumn is used to define columns for use in the library. SqlColumns should be created using the builder methods in SqlTable. A column definition includes:

  1. The Java type
  2. The actual column name (an alias can be applied in a select statement)
  3. The JDBC type
  4. (optional) The name of a type handler to use in MyBatis if the default type handler is not desired

We suggest the following usage pattern to give maximum flexibility. This pattern will allow you to use your table and columns in a "qualified" or "un-qualified" manner that looks like natural SQL. For example, in the following a column could be referred to as firstName or simpleTable.firstName.

package examples.simple;

import java.sql.JDBCType;
import java.util.Date; import org.mybatis.dynamic.sql.SqlColumn;
import org.mybatis.dynamic.sql.SqlTable; public final class SimpleTableDynamicSqlSupport {
public static final SimpleTable simpleTable = new SimpleTable();
public static final SqlColumn<Integer> id = simpleTable.id;
public static final SqlColumn<String> firstName = simpleTable.firstName;
public static final SqlColumn<String> lastName = simpleTable.lastName;
public static final SqlColumn<Date> birthDate = simpleTable.birthDate;
public static final SqlColumn<Boolean> employed = simpleTable.employed;
public static final SqlColumn<String> occupation = simpleTable.occupation; public static final class SimpleTable extends SqlTable {
public final SqlColumn<Integer> id = column("id", JDBCType.INTEGER);
public final SqlColumn<String> firstName = column("first_name", JDBCType.VARCHAR);
public final SqlColumn<String> lastName = column("last_name", JDBCType.VARCHAR);
public final SqlColumn<Date> birthDate = column("birth_date", JDBCType.DATE);
public final SqlColumn<Boolean> employed = column("employed", JDBCType.VARCHAR, "examples.simple.YesNoTypeHandler");
public final SqlColumn<String> occupation = column("occupation", JDBCType.VARCHAR); public SimpleTable() {
super("SimpleTable");
}
}
}

Second - Write MyBatis mappers that will use the generated statement

The library will create classes that will be used as input to a MyBatis mapper. These classes include the generated SQL, as well as a parameter set that will match the generated SQL. Both are required by MyBatis. It is intended that these objects be the one and only parameter to a MyBatis mapper method.

The library can be used with both XML and annotated mappers, but we recommend using MyBatis' annotated mapper support in all cases. The only case where XML is required is when you code a JOIN statement - in that case you will need to define your result map in XML due to limitations of the MyBatis annotations in supporting joins.

For example, a mapper might look like this:

package examples.simple;

import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.SelectProvider;
import org.mybatis.dynamic.sql.delete.render.DeleteStatementProvider;
import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
import org.mybatis.dynamic.sql.util.SqlProviderAdapter; public class SimpleTableAnnotatedMapper { @SelectProvider(type=SqlProviderAdapter.class, method="select")
@Results(id="SimpleTableResult", value= {
@Result(column="A_ID", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="first_name", property="firstName", jdbcType=JdbcType.VARCHAR),
@Result(column="last_name", property="lastName", jdbcType=JdbcType.VARCHAR),
@Result(column="birth_date", property="birthDate", jdbcType=JdbcType.DATE),
@Result(column="employed", property="employed", jdbcType=JdbcType.VARCHAR, typeHandler=YesNoTypeHandler.class),
@Result(column="occupation", property="occupation", jdbcType=JdbcType.VARCHAR)
})
List<SimpleTableRecord> selectMany(SelectStatementProvider selectStatement); @DeleteProvider(type=SqlProviderAdapter.class, method="delete")
int delete(DeleteStatementProvider deleteStatement);
}

Third - Create dynamic statements

Select statements are created by combining your column and table definitions (from the first step above) with condition for the column. This library includes a large number of type safe conditions. All SQL construction methods can be accessed through expressive static methods in the org.mybatis.dynamic.sql.SqlBuilder interface.

For example, a very simple select statement can be defined like this:

        SelectStatementProvider selectStatement = select(count())
.from(simpleTable)
.where(id, isEqualTo(3))
.build()
.render(RenderingStrategy.MYBATIS3);

Or this (also note that you can give a table an alias):

        SelectStatementProvider selectStatement = select(count())
.from(simpleTable, "a")
.where(id, isNull())
.build()
.render(RenderingStrategy.MYBATIS3);

A delete statement looks like this:

        DeleteStatementProvider deleteStatement = deleteFrom(simpleTable)
.where(occupation, isNull())
.build()
.render(RenderingStrategy.MYBATIS3);

The "between" condition is also expressive:

        SelectStatementProvider selectStatement = select(count())
.from(simpleTable)
.where(id, isBetween(1).and(4))
.build()
.render(RenderingStrategy.MYBATIS3);

More complex expressions can be built using the "and" and "or" conditions as follows:

        SelectStatementProvider selectStatement = select(count())
.from(simpleTable)
.where(id, isGreaterThan(2))
.or(occupation, isNull(), and(id, isLessThan(6)))
.build()
.render(RenderingStrategy.MYBATIS3);

All of these statements rely on a set of expressive static methods. It is typical to import the following:

// import all column definitions for your table
import static examples.simple.SimpleTableDynamicSqlSupport.*; // import the SQL builder
import static org.mybatis.dynamic.sql.SqlBuilder.*;

Fourth - Use your statements

In a DAO or service class, you can use the generated statement as input to your mapper methods. Here's an example from examples.simple.SimpleTableAnnotatedMapperTest:

    @Test
public void testSelectByExample() {
SqlSession session = sqlSessionFactory.openSession();
try {
SimpleTableXmlMapper mapper = session.getMapper(SimpleTableXmlMapper.class); SelectStatementProvider selectStatement = select(id.as("A_ID"), firstName, lastName, birthDate, employed, occupation)
.from(simpleTable)
.where(id, isEqualTo(1))
.or(occupation, isNull())
.build()
.render(RenderingStrategy.MYBATIS3); List<SimpleTableRecord> rows = mapper.selectMany(selectStatement); assertThat(rows.size()).isEqualTo(3);
} finally {
session.close();
}
}

The code in the folder src/test/java/examples/simple shows how to use the library for INSERT and UPDATE statements in addition to the examples shown here. It shows a suggested usage of the library to enable a complete range of CRUD operations on a database table. Lastly, it is an example of the code that could be created by a future version of MyBatis Generator.

【生成一个字符串】

以字符串生成的视角分析sql-builder:仅仅是一个类,可以方便地生成坚固sql形式得字符串

2013年04月18日

在MyBatis的映射配置文件中写sql语句有时候很方便,但是对于有大量字段的表结构却不太简单,幸好MyBatis提供的有SqlBuilder工具类

MyBatis学习3---使用SqlBuilder生成SQL语句 - 一路博客 - CSDN博客 https://blog.csdn.net/wyc_cs/article/details/8820500

package com.neo.sqlBuilder;
import org.apache.ibatis.jdbc.SQL; public class GenStr { // With conditionals (note the final parameters, required for the anonymous inner class to access them)
public String selectPersonLike(final String id, final String firstName, final String lastName) {
return new SQL() {{
SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME");
FROM("PERSON P");
if (id != null) {
WHERE("P.ID like #{id}");
}
if (firstName != null) {
WHERE("P.FIRST_NAME like #{firstName}");
}
if (lastName != null) {
WHERE("P.LAST_NAME like #{lastName}");
}
ORDER_BY("P.LAST_NAME");
}}.toString();
} public static void main(String[] args) {
GenStr genStr = new GenStr();
System.out.println("查询 = " + genStr.selectPersonLike("123","456","789"));
} }

查询 = SELECT P.ID, P.USERNAME, P.PASSWORD, P.FIRST_NAME, P.LAST_NAME
FROM PERSON P
WHERE (P.ID like #{id} AND P.FIRST_NAME like #{firstName} AND P.LAST_NAME like #{lastName})
ORDER BY P.LAST_NAME

对比

D:\worksp\springtest\src\main\java\com\neo\controller\HelloController.java

@RequestMapping("/testMyBaitsInsert")
public String testMyBaits() throws IOException {
String res = this.getClass().getName() + Thread.currentThread().getStackTrace()[1].getMethodName(); Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
try {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
try {
//Create a new student object
Student student;
for (int i = 0; i < 10; i++) {
student = new Student("Mohammad", "It", 80, i * i, System.currentTimeMillis() + "Mohammad@gmail.com");
//Insert student data
session.insert("Student.insert", student); # 注意
System.out.println("record inserted successfully" + Integer.toString(i));
}
session.commit();
} finally {
session.close();
}
} catch (IndexOutOfBoundsException e) {
System.err.println("IndexOutOfBoundsException: " + e.getMessage());
}
return res;
}

【生成一个相当于xml中配置文件的字符串】

sql构造器的作用,在此相当于xml配置文件中的语句

using the library to generate a dynamic SELECT or DELETE statement mysqlbaits xml配置文件 与 sql构造器 对比的更多相关文章

  1. DBMS客户端是否安装:Make sure DBMS client is installed and this required library is available for dynamic loading

    Symptom The full error message is as follows:Error logging in.  Unable to process the database trans ...

  2. Laravel - Union + Paginate at the same time? and another problem----1222 The used SELECT statements have a different number of columns (SQL: (select count(*) as aggregate from

    ### 这是这几天,碰到的一个比较头疼的问题 使用union all联合查询,同时laravel 生成分页,但发生报错? QueryException : SQLSTATE The used from ...

  3. Mybaits 源码解析 (六)----- 全网最详细:Select 语句的执行过程分析(上篇)(Mapper方法是如何调用到XML中的SQL的?)

    上一篇我们分析了Mapper接口代理类的生成,本篇接着分析是如何调用到XML中的SQL 我们回顾一下MapperMethod 的execute方法 public Object execute(SqlS ...

  4. 用mybatis将SQL查询语句”select * from user”的封装为配置文件

    用mybatis将SQL查询语句”select * from user”的封装为配置文件 定义一个xml映射文件,文件名见名知意.如user-mapper.xml,文件内容如下: <?xml v ...

  5. Eclipse导入工程后,XDoclet错误:Missing library: xdoclet-1.2.1.jar. Select the home directory for XDoclet

    这几天在使用Open Health Tools的OpenXDS工程,在导入Eclipse后,出现下面的错误: 遂google之,在网上找到了答案.答案网址为http://blog.v-s-f.co.u ...

  6. 使用dynamic动态设置属性值与反射设置属性值性能对比

    static void Main(string[] args) { int times = 1000000; string value = "Dynamic VS Reflection&qu ...

  7. [Hibernate] - Select/Update/Delete/Insert

    Java bean: package com.my.bean; import java.util.Date; public class WorkPack { private String uWorkP ...

  8. 探究如何永久更改Maven的Dynamic Web Project版本及pom.xml默认配置

    一:问题 在用eclipse创建一个maven project (webApp)时,我们一般会要进行许多麻烦的配置,比如 1.更改Java jdk版本为1.7或1.8(默认1.5) 2.补全src/m ...

  9. Dapper的基本使用,Insert、Update、Select、Delete

    简介 Dapper是.NET下一个micro的ORM,它和Entity Framework或Nhibnate不同,属于轻量级的,并且是半自动的.也就是说实体类都要自己写.它没有复杂的配置文件,一个单文 ...

随机推荐

  1. 关于lockkeyword

    线程同步对象keywordlock,是以lock相应的object对象为准,即随意线程lock住lockObj对象之后,其它线程不管在其它不论什么代码段使用lock(lockObj)去进行线程同步时, ...

  2. (转载)UTF-8和GBK的编码方式的部分知识:重要

    GBK的文字编码是双字节来表示的,即不论中.英文字符均使用双字节来表示,只不过为区分中文,将其最高位都定成1. 至于UTF-8编码则是用以解决国际上字符的一种多字节编码,它对英文使用8位(即一个字节) ...

  3. CentOS查看操作系统信息(重要)

    1.查看物理CPU的个数 [root@MysqlCluster01 ~]# cat /proc/cpuinfo |grep "physical id"|sort |uniq|wc ...

  4. u3d调用c++ dll的DllNotFoundExceion 问题

    原文地址:http://blog.csdn.net/boren31/article/details/8778504 问题年年有,今年特别多. 开发环境: Windows  XP sp3 Visual  ...

  5. 对sssp项目搭建的补充,总错误处理。

    总错误处理,是为了在程序运行时代码出错能及时在控制台看出错误信息. 1. springMVC配置文件中: -------- 2.controller包中: 新建类FrameControllerAdvi ...

  6. GLSL/C++ 实现滤镜效果

    入门效果之浮雕 "浮雕"图象效果是指图像的前景前向凸出背景.常见于一些纪念碑的雕刻上.要实现浮雕事实上很easy.我们把图象的一个象素和左上方的象素进行求差运算.并加上一个灰度.这 ...

  7. Linux 下安装 Python3

    Linux CentOS 7 安装 Python3: [root@localhost ~]$ yum install -y epel-release [root@localhost ~]$ yum i ...

  8. OAuth2认证有一定的了解

    转到分享界面后,进行OAuth2认证: 以新浪为例: 第一步.WebView加载界面,传递参数 使用WebView加载登陆网页,通过Get方法传递三个参数:应用的appkey.回调地址和展示方式dis ...

  9. 告别C#,进入了下一个阶段的学习啦

    嘿嘿,今天我们结束了C#的基础的学习,开始啦第二个阶段的学习,就是对SQL Server的学习.今天又是一个周一,又是一个新的开始,感觉我们都是一周一周的计算,而不是每天到这个点就是告别了今天的生活啦 ...

  10. UIImageView 和 UIWebView 小结

    本文转载至:http://www.cnblogs.com/huangdongcheng/archive/2011/11/21.html 1.UIImageView的讲解 (1)初始化 UIImageV ...