本文是关于mybatis的早期使用方法。
0.前期准备
1 | CREATE TABLE tb_employee |
POJO类:1
2
3
4
5
6
7
8
9
10
11
12public class TbEmployee {
private long id;
private String loginname;
private String password;
private String name;
private String sex;
private long age;
private String phone;
private double sal;
private String state;
//getter,setter
1.xml配置
1 |
|
2.测试
1 | public class DynamicSQLTest { |
1 | //output: |
使用like的另一种写法:1
2
3
4
5
6
7
8
9
10
11
12<select id="getUsersByConditionIf" resultType="com.model.User" parameterType="com.model.User">
select * from user where
<if test="id!=null">
id = #{id}
</if>
<if test="username!=null and username !=''">
or username like "%"#{username}"%"
</if>
<if test="sex != null">
and sex = #{sex}
</if>
</select>
使用”%”#{parameter}”%”,运行结果如下:1
2
3
4
5
6
7
8
9
10
11DEBUG [main] - ==> Preparing: select id, username,birthday, sex, address,dept_id from user where id = ?
DEBUG [main] - ==> Parameters: 27(Integer)
DEBUG [main] - <== Total: 1
DEBUG [main] - ==> Preparing: select id, name from department where id = ?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
User{id=27, username='tes111t', birthday=Thu Jul 12 08:00:00 CST 2018, sex='1', address='1'}
DEBUG [main] - ==> Preparing: select * from user where id = ? or username like "%"?"%" and sex = ?
DEBUG [main] - ==> Parameters: 27(Integer), 1(String), 1(String)
DEBUG [main] - <== Total: 2
[User{id=27, username='tes111t', birthday=Thu Jul 12 08:00:00 CST 2018, sex='1', address='1'}, User{id=32, username='11231', birthday=Thu Jul 12 08:00:00 CST 2018, sex='1', address='1'}]
要使每个1
select * from xxx where 1=1
这样保证每个
也可以使用where标签将所有拼接的动态条件放入。
但是where只能去掉第一个and。
一次更新多条数据:1
void addUsers(@Param("userList") List<User> userList);
1 | <insert id="addUsers" > |
需要插入别的字段需要自己加入。