mybatis--MyBatis动态SQL语句
1. if 语句 (简单的条件判断)
2. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.
3. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)
4. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误)
5. set (主要用于更新时)
6. foreach (用于mybatis语句查询)
(3)建立com.zk.dao包下的IUser接口:
IUser.java
package com.zk.dao; import org.apache.ibatis.annotations.Param;
import com.zk.pojo.User; public interface IUser {
public User findUserWithNameLike(@Param("id")int id, @Param("name")String name);
}
(4)在com.zk.pojo包下建立User实现IUser接口中的方法,并配置UserMapper.xml
User.java
package com.zk.pojo; public class User {
private int id;
private String name;
private String level;
private String phone;
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 getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", level=" + level
+ ", phone=" + phone + "]";
}
}
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="com.zk.dao.IUser">
<select id="findUserWithNameLike" resultType="User">
SELECT * FROM user
WHERE id = #{id} <if test="name!= null">
AND name like #{name}
</if>
</select>
</mapper>
(5)配置config/configure.xml
configure.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>
<typeAliases>
<typeAlias alias="User" type="com.zk.pojo.User" />
</typeAliases> <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://localhost:3306/my"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments> <mappers>
<!-- // power by http://www.yiibai.com -->
<mapper resource="com/zk/pojo/UserMapper.xml" />
</mappers>
</configuration>
(6)实现main函数
MainApp.java
package Main; import java.io.IOException;
import java.io.Reader; 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 com.zk.dao.IUser;
import com.zk.pojo.User; public class MainApp {
private static SqlSessionFactory sqlsessionfactory;
private static Reader reader; static{
try {
reader=Resources.getResourceAsReader("config/configure.xml");
sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public SqlSessionFactory getSqlSessionFactory()
{
return sqlsessionfactory;
} public static void main(String[]args)
{
select(1,"c");
} public static void select(int id,String name){
//获取session连接
SqlSession session=sqlsessionfactory.openSession();
//获取mapper
IUser usermap=session.getMapper(IUser.class);
//selectAllUser();
User user = usermap.findUserWithNameLike(id, name);
//执行查询
System.out.println(user.toString());
session.commit();
//selectAllUser();
}
}
Main执行结果如下:
2. where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误)
(1) 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="com.zk.dao.IUser">
<select id="findUserWithNameLike" resultType="User">
SELECT * FROM user
<where> <if test="id!=null">id like #{id}</if>
<if test="name!=null">AND name like #{name}</if>
</where>
</select>
</mapper>
运行结果如下:
3. choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.
同样原始的数据库,仅更改pojo层的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="com.zk.dao.IUser">
<select id="findUserWithNameLike" resultType="User">
SELECT * FROM user where
<choose>
<when test="id!=null">
id like #{id}
</when>
<when test="name!=null">
AND name like #{name}
</when>
</choose> </select>
</mapper>
运行后得到的结果如下图所示:
4. set (主要用于更新时)
(1)IUser.java
package com.zk.dao; import com.zk.pojo.User; public interface IUser {
public User updateUser(User user);
}
(2)UserMapper.xml和User.java
User.java
package com.zk.pojo; public class User {
private int id;
private String name;
private String level;
private String phone;
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 getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", level=" + level
+ ", phone=" + phone + "]";
}
}
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="com.zk.dao.IUser">
<update id="updateUser" parameterType="User">
update user
<set>
<if test="name!=null">name=#{name},</if>
<if test="level!=null">level=#{level},</if>
<if test="phone!=null">phone=#{phone}</if>
</set>
where id=#{id}
</update>
</mapper>
(3)configure.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>
<typeAliases>
<typeAlias alias="User" type="com.zk.pojo.User" />
</typeAliases> <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://localhost:3306/my"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="com/zk/pojo/UserMapper.xml" />
</mappers>
</configuration>
(4)Main.java
package Main; import java.io.IOException;
import java.io.Reader; 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 com.zk.dao.IUser;
import com.zk.pojo.User; public class MainApp {
private static SqlSessionFactory sqlsessionfactory;
private static Reader reader; static{
try {
reader=Resources.getResourceAsReader("config/configure.xml");
sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public SqlSessionFactory getSqlSessionFactory()
{
return sqlsessionfactory;
} public static void main(String[]args)
{
SqlSession session=sqlsessionfactory.openSession();
User user=new User();
user.setId(1);
user.setName("a");
user.setLevel("a");
user.setPhone("137298647"); session.update("updateUser",user);
session.commit();
}
}
运行结果如下:
5. trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)
IUser.java
package com.zk.dao; import org.apache.ibatis.annotations.Param;
import com.zk.pojo.User; public interface IUser {
public User findUserWithNameLike(@Param("id")int id, @Param("name")String name);
}
User.java
package com.zk.pojo; public class User {
private int id;
private String name;
private String level;
private String phone;
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 getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", level=" + level
+ ", phone=" + phone + "]";
}
}
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="com.zk.dao.IUser">
<select id="findUserWithNameLike" resultType="User">
SELECT * FROM user
<trim prefix="WHERE" prefixOverrides="AND">
<if test="id!=null">
id=#{id}
</if>
<if test="name!= null">
AND name like #{name}
</if>
</trim>
</select>
</mapper>
MainApp.java
package Main; import java.io.IOException;
import java.io.Reader; 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 com.zk.dao.IUser;
import com.zk.pojo.User; public class MainApp {
private static SqlSessionFactory sqlsessionfactory;
private static Reader reader; static{
try {
reader=Resources.getResourceAsReader("config/configure.xml");
sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public SqlSessionFactory getSqlSessionFactory()
{
return sqlsessionfactory;
} public static void main(String[]args)
{
select(1,"a");
} public static void select(int id,String name){
//获取session连接
SqlSession session=sqlsessionfactory.openSession();
//获取mapper
IUser usermap=session.getMapper(IUser.class);
//selectAllUser();
User user = usermap.findUserWithNameLike(id, name);
//执行查询
System.out.println(user.toString());
session.commit();
//selectAllUser();
}
}
执行结果如下:
6. foreach (用于mybatis语句查询)
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="com.zk.dao.IUser">
<select id="findUsersWithIdforeach" resultType="User">
SELECT * FROM user
<where>id in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</where>
</mapper>
IUser.java
package com.zk.dao; import java.util.List;
import org.apache.ibatis.annotations.Param; import com.zk.pojo.User; public interface IUser {
public List<User> findUsersWithIdforeach(@Param("list")List<Integer> list);
}
Main.java
package Main; import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List; 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 com.zk.dao.IUser;
import com.zk.pojo.User; public class MainApp {
private static SqlSessionFactory sqlsessionfactory;
private static Reader reader; static{
try {
reader=Resources.getResourceAsReader("config/configure.xml");
sqlsessionfactory=new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public SqlSessionFactory getSqlSessionFactory()
{
return sqlsessionfactory;
} public static void main(String[]args)
{
select(1,"a");
} public static void select(int id,String name){
//获取session连接
SqlSession session=sqlsessionfactory.openSession();
//获取mapper
IUser usermap=session.getMapper(IUser.class);
//selectAllUser();
List ids=new ArrayList();
ids.add(1);
ids.add(2);
ids.add(3);
ids.add(4);
//执行查询
//System.out.println(user.toString());
List<User> users=usermap.findUsersWithIdforeach(ids);
for(User u:users)
{
System.out.println(u);
}
session.commit();
//selectAllUser();
}
}
程序运行结果:
数据库中数据:
mybatis--MyBatis动态SQL语句的更多相关文章
- mybatis 的动态sql语句是基于OGNL表达式的。
mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:1. if 语句 (简单的条件判断)2. c ...
- MyBatis中动态SQL语句完成多条件查询
一看这标题,我都感觉到是mybatis在动态SQL语句中的多条件查询是多么的强大,不仅让我们用SQL语句完成了对数据库的操作:还通过一些条件选择语句让我们SQL的多条件.动态查询更加容易.简洁.直观. ...
- Mybatis中动态SQL语句中的parameterType不同数据类型的用法
Mybatis中动态SQL语句中的parameterType不同数据类型的用法1. 简单数据类型, 此时#{id,jdbcType=INTEGER}中id可以取任意名字如#{a,jdbcType ...
- MyBatis 构造动态 SQL 语句
以前看过一个本书叫<深入浅出 MFC >,台湾 C++ 大师写的一本书.在该书中写到这样一句话,“勿在浮沙筑高台”,这句话写的的确对啊.编程很多语言虽然相通,但是真正做还是需要认真的学习, ...
- Mybatis 的动态 SQL 语句
<if>标签 我们根据实体类的不同取值,使用不同的 SQL 语句来进行查询. 比如在 id 如果不为空时可以根据 id 查询, 如果 username 不同空时还要加入用户名作为条件.这种 ...
- 阶段3 1.Mybatis_08.动态SQL_03.mybatis中动态sql语句-foreach和sql标签
foreach标签 in的查询 sql语句好写,但是传参在映射文件里面改怎么传呢 定义一个List<Integer>成员变量,然后生成get和set 定义一个新的查询方法 open:开始符 ...
- 阶段3 1.Mybatis_08.动态SQL_02.mybatis中动态sql语句-where标签的使用
这里的userSex是实体类里面的属性名,而不是数据库内的字段名称 一个老王改成性别女,为了区分一下 增加sex字段的查询 where标签 用上where和刚才的执行效果是一样的 where标签使我们 ...
- mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句
mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:1. if 语句 (简单的条件判断)2. c ...
- 【转】mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句
转自:除非申明,文章均为一号门原创,转载请注明本文地址,谢谢! 转载地址:http://blog.csdn.net/kutejava/article/details/9164353#t5 1. if ...
- Mybatis学习笔记(四) 之动态SQL语句
动态SQL mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类: 1. if 语句 (简单的条件 ...
随机推荐
- Dubbo快速入门
Dubbo作为一个RPC框架,其最核心的功能就是要实现跨网络的远程调用.这次创建两个应用,一个作为服务的提供方,一个作为服务的消费方.通过Dubbo来实现服务消费方远程调用服务提供方的方法. 服务提供 ...
- 最长公共子串2(LCS2) lg SP1812
题意:n个字符串(n<=10)求最长公共子串的长度 前置技能点:https://www.cnblogs.com/wenci/p/10432932.html (两个字符串求最长公共子串的长度) 既 ...
- C语言链表的中间结点
给定一个带有头结点 head 的非空单链表,返回链表的中间结点. 如果有两个中间结点,则返回第二个中间结点. 示例 1: 输入:[1,2,3,4,5]输出:此列表中的结点 3 (序列化形式:[3,4, ...
- Oracle监听出现的问题总结,以及解决办法
包括的错误类型: 1.ORA-12541: TNS: 无监听程序 2. ORA-12514: TNS: 监听程序当前无法识别连接描述符中请求的服务 3.ORA-12560: TNS: 协议适配器错误 ...
- navicat连接mysql查询结果中文都是?号(C#)
记录解决方法,方便以后查看. 有几个地方需要注意: 1.连接mysql数据库的字符串最后加上Charset=utf8; 2.mysql中character_set_XX设置都为utf8,使用show ...
- 用C#调用外部DLL
1.有时候需要用C#调用外部的dll,例如c++写的dll,首先需要保证dll的编译环境与本项目的环境是相同的,例如都是x86位或者x64位 2.调用声明和dll内的声明一致: function Te ...
- Appium连接模拟器
Appnium 环境搭建 覆盖文件 将SDK中platform-tools目录下的这三个文件 复制到模拟安装路径bin目录下,覆盖原有的这三个文件 adb命令 开启服务 adb start-serve ...
- 洛谷P1086 花生采摘
https://www.luogu.org/problem/P1086 #include <bits/stdc++.h> using namespace std; typedef long ...
- SGD 讲解,梯度下降的做法,随机性。理解反向传播
SGD 讲解,梯度下降的做法,随机性.理解反向传播 待办 Stochastic Gradient Descent 随机梯度下降没有用Random这个词,因为它不是完全的随机,而是服从一定的分布的,只是 ...
- 题解【洛谷P5958】[POI2017]Sabotaż
题面 考虑树形 \(\text{DP}\). 设 \(dp_i\) 为使 \(i\) 变成叛徒的最大值,同时 \(dp_i\) 也是使 \(i\) 不变成叛徒的最小值. 然后考虑如何转移状态. 如果 ...