11.2 基于注解的动态SQL2 insert

动态生成基于注解形式的insert语句

动态生成SQL代码的方法

/MyADynamicSQLTest/src/mapper/EmployeeDynamicSQLProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public String insertEmployeeWithParamPO(Employee employee)
{
return new SQL() {
{
// 在这里写上动态SQL的生成逻辑...
INSERT_INTO("tb_employee");
if (employee.getId() != null)
{
VALUES("id", "#{id}");
}
if (employee.getLoginname() != null)
{
VALUES("loginname", "#{loginname}");
}
if (employee.getPassword() != null)
{
VALUES("password", "#{password}");
}
if (employee.getName() != null)
{
VALUES("name", "#{name}");
}
if (employee.getSex() != null)
{
VALUES("sex", "#{sex}");
}
if (employee.getAge() != null)
{
VALUES("age", "#{age}");
}
if (employee.getPhone() != null)
{
VALUES("phone", "#{phone}");
}
if (employee.getSal() != null)
{
VALUES("sal", "#{sal}");
}
if (employee.getState() != null)
{
VALUES("state", "#{state}");
}
}
}.toString();
}

mapper接口方法

1
2
3
4
5
6
7
8
9
10
@InsertProvider(
type = EmployeeDynamicSQLProvider.class,
method = "insertEmployeeWithParamPO"
)
// 设置使用自动增长主键,主键返回给po类的id属性
@Options(
useGeneratedKeys = true,
keyProperty = "id"
)
int insertEmployeeWithParmPO(Employee employee);

这里使用了两个注解,一个注解是@InsertProvider注解,该注解的type属性支持生成动态SQL的类,method属性指出生成动态SQL的具体方法.
@Options注解的useGeneratedKeys属性表示是否使用自动增长的主键,keyProperty属性表示用于持久化对象接收生成的主键的属性

测试类insertTest.java

/MyADynamicSQLTest/src/test/insertTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package test;

import org.apache.ibatis.session.SqlSession;
import domain.Employee;
import fractory.SqlSessionFactoryTools;
import mapper.EmployeeMapper;

public class insertTest {
public static void main(String[] args) {
SqlSession sqlSession = null;
try {
// 加载mybatis-config.xml,获取SqlSession实例
sqlSession = SqlSessionFactoryTools.getSqlSession();
// 获取mapper接口代理对象
EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
Employee employee = new Employee();
// employee.setLoginname("xiaozhang");
// employee.setPassword("xiaozhang");
employee.setName("小张");
employee.setSex("男");
employee.setAge(22);
employee.setPhone("123456789123");
employee.setSal(6800.0);
employee.setState("经理");
employeeMapper.insertEmployeeWithParmPo(employee);
System.out.println("生成的主键:" + employee.getId());
// 提交事务
sqlSession.commit();
} catch (Exception e) {
// 出错回滚事务
sqlSession.rollback();
e.printStackTrace();
} finally {
// 关闭会话
if (sqlSession != null)
sqlSession.close();
}

}
}

运行该测试类,给持久化对象的一些属性赋值,然后调用mapper接口的方法把信息插入到数据库中。mybatis会根据参数设置的数据动态生成valuse子句.运行效果如下所示:

DEBUG [main] ==>  Preparing: INSERT INTO tb_employee (name, sex, age, phone, sal, state) VALUES (?, ?, ?, ?, ?, ?) 
DEBUG [main] ==> Parameters: 小张(String), 男(String), 22(Integer), 123456789123(String), 6800.0(Double), 经理(String)
DEBUG [main] <==    Updates: 1
生成的主键:5