动态生成基于注解形式的insert语句
动态生成SQL代码方法
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() { { 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" )
@Options( useGeneratedKeys = true, keyProperty = "id" ) int insertEmployeeWithParmPO(Employee employee);
|
这里使用了两个注解,一个注解是@InsertProvider
注解,该注解的type
属性支持生成动态SQL
的类,method
属性指出生成动态SQL
的具体方法.
@Options
注解的useGeneratedKeys
属性表示是否使用自动增长的主键,keyProperty
属性表示用于持久化对象接收生成的主键的属性
测试类
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
| package test; import org.apache.ibatis.session.SqlSession; import domain.Employee; import fractory.SqlSessionFratoryTools; import mapper.EmployeeMapper; public class insertTest { public static void main(String[] args) { SqlSession sqlSession = null; try { sqlSession = SqlSessionFratoryTools.getSqlSession(); EmployeeMapper employeeMapper = sqlSession.getMapper(EmployeeMapper.class); Employee employee = new Employee(); 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
子句.运行效果如下所示:
1 2 3 4
| 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
|
原文链接: 11.2 基于注解的动态SQL2 insert