关于mybatis的<selectKey>中的keyColumn
<mapper namespace="com.dao.EmployeeDao"> <insert id="insert"> <selectKey order="BEFORE" keyColumn="employeeId,employeeGender" keyProperty="employeeId,employeeGender" resultType="com.entity.Employee"> select employee_id employeeId,employee_gender employeeGender from employee where employee_id=13 </selectKey> insert into subtable(employee_id,employee_name,employee_gender) values (#{employeeId},"mdzz",#{employeeGender}) </insert> </mapper>
keyColumn是要和select语句中的表名相对应的实体类的字段对应的,但同时他也要和select语句中的列名对应,因此要取别名一致。
keyProperty是和insert语句中的values内的参数一致,也就是和insert语句中的表的对应实体类的字段一致,才可以通过反射完成
java代码
public interface EmployeeDao { int insert(Employee employee); }
测试代码
@Test public void testInsert() { Employee employee = new Employee(); EmployeeDao employeeDao = MapperFactory.generateMapper(EmployeeDao.class); employeeDao.insert(employee); System.out.println(employee); }
表说明:创建了一个employee表,和一个副标subtable,列和employee完全一样,列名都是通过“_”连接的
employee | CREATE TABLE `employee` ( `employee_id` int(11) NOT NULL AUTO_INCREMENT, `employee_name` char(30) DEFAULT NULL, `employee_gender` binary(1) DEFAULT NULL, `employee_salary` decimal(10,2) DEFAULT NULL, `dept_id` int(11) DEFAULT NULL, PRIMARY KEY (`employee_id`) ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8mb4 |