在使用mybatis时传入参数的3种方式:
1、 对象做参数,需要对象使用到的属性 get/set方法
int updateByPrimaryKey(Employee record);
<insert id="insert" parameterType="com.lls.model.Employee">
<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="id">
SELECT LAST_INSERT_ID() AS ID
</selectKey>
insert into t_employee (ID, EmployeeName, Position,
Salary, Tel, DepartmentID
)
values (#{id,jdbcType=INTEGER}, #{employeename,jdbcType=VARCHAR}, #{position,jdbcType=VARCHAR},
#{salary,jdbcType=DOUBLE}, #{tel,jdbcType=VARCHAR}, #{departmentid,jdbcType=INTEGER}
)
</insert>
2、注解做参数,参数不太多时用
List<Employee> selectByDepartmentID(@Param("departmentID")int departmentID, @Param("salary")double salary);<select id="selectByDepartmentID" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_employee
where DepartmentID = #{departmentID,jdbcType=INTEGER} and Salary >= #{salary,jdbcType=DOUBLE}
</select>
3、map放入参数,可以方便扩展
List<Employee> selectByDepartmentIDMap(Map<String, Object> paramMap);
<select id="selectByDepartmentIDMap" parameterType="java.util.Map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_employee
where DepartmentID = #{departmentID,jdbcType=INTEGER} and Salary >= #{salary,jdbcType=DOUBLE}
</select>
测试: package com.lls.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.lls.mapper.EmployeeMapper;
import com.lls.model.Employee;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:config/spring-mybatis.xml"})
public class MyBatisParam {
private static final Logger LOGGER = LoggerFactory.getLogger(MyBatisParam.class);
@Autowired
private EmployeeMapper employeeMapper;
@Test
public void paramObjTest() {
/*
* 对象做参数,需要对象使用到的属性 get/set方法
*/
Employee employee = new Employee();
employee.setDepartmentid(1);
employee.setEmployeename("xiaoA");
employee.setPosition("manager");
employee.setSalary(13000d);
int result = employeeMapper.insert(employee);
LOGGER.info("result: "+result);
}
@Test
public void paramAnnotationTest() {
/*
* 注解做参数,参数不太多时用
*/
List<Employee> employees = employeeMapper.selectByDepartmentID(1,12000d);
LOGGER.info("employees.size: "+employees.size());
}
@Test
public void paramMapTest() {
/*
* map放入参数,可以方便扩展
*/
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("departmentID", 1);
paramMap.put("salary", 12000d);
List<Employee> employees = employeeMapper.selectByDepartmentIDMap(paramMap);
LOGGER.info("employees.size: "+employees.size());
}
}
代码文档:http://download.csdn.net/download/lanlianhua_luffy/9869769