MyBatis学习3---使用SqlBuilder生成SQL语句

在MyBatis的映射配置文件中写sql语句有时候很方便,但是对于有大量字段的表结构却不太简单,幸好MyBatis提供的有SqlBuilder工具类,可以生成相应的SQL语句,如下例程:

package com.utils;

import org.apache.ibatis.jdbc.SqlBuilder;

public class MyBatisUtils extends SqlBuilder {
	public String selectUserSql() {
		BEGIN();
		SELECT("*");
		FROM("UserDto");
		return SQL();
	}

	public String deleteUserSql() {
		BEGIN();
		DELETE_FROM("UserDto");
		WHERE("username = #{username}");
		return SQL();
	}

	public String insertUserSql() {
		BEGIN();
		INSERT_INTO("UserDto");
		VALUES("username", "#{username}");
		VALUES("password", "#{password}");
		VALUES("address", "#{address}");
		VALUES("age", "#{age}");
		VALUES("sex", "#{sex}");
		return SQL();
	}

	public String updateUserSql() {
		BEGIN();
		UPDATE("UserDto");
		SET("password = #{password}");
		WHERE("username = #{username}");
		return SQL();
	}

	public static void main(String[] args) {
		MyBatisUtils myBatisUtils = new MyBatisUtils();
		System.out.println("查询 = " + myBatisUtils.selectUserSql());
		System.out.println("删除 = " + myBatisUtils.deleteUserSql());
		System.out.println("插入 = " + myBatisUtils.insertUserSql());
		System.out.println("更新 = " + myBatisUtils.updateUserSql());
	}
}

更多文章见: http://www.16boke.com

你可能感兴趣的:(MyBatis学习3---使用SqlBuilder生成SQL语句)