mybatis-210718-03—映射文件_参数处理_POJO_Map_TO
POJO:
如果多个参数正好是我们业务逻辑的数据模型,我们就可以直接传入pojo
#{属性名}:取出传入的pojo的属性值
Map:
如果多个参数不是业务模型中的数据,没有对应的pojo,为了方便,我们也可以传入map
#{key}:取出map中对应的值
TO:
如果多个参数不是业务模型中的数据,但是经常使用,推荐来编写了TO(Transfer Object)数据传输对象
page{
int index;
int size;
}
Map示例
EmployeeMapper.java
package com. bgy. mybatis. dao ;
import java. util. Map ;
import org. apache. ibatis. annotations. Param ;
import com. bgy. mybatis. bean. Employee ;
public interface EmployeeMapper {
public Employee getEmpByMap ( Map < String , Object > map) ;
}
EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<! DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
< mapper namespace = " com.bgy.mybatis.dao.EmployeeMapper" >
< select id = " getEmpByMap" resultType = " com.bgy.mybatis.bean.Employee" >
select
id,last_name,gender,email
from
tbl_employee
where
id = #{id} and last_name=#{lastName}
</ select>
</ mapper>
MybatisTest.java
package com. bgy. mybatis. test ;
import static org. junit. jupiter. api. Assertions . *;
import java. io. IOException ;
import java. io. InputStream ;
import java. util. HashMap ;
import java. util. Map ;
import org. apache. ibatis. io. Resources ;
import org. apache. ibatis. session. SqlSession ;
import org. apache. ibatis. session. SqlSessionFactory ;
import org. apache. ibatis. session. SqlSessionFactoryBuilder ;
import org. junit. jupiter. api. Test ;
import com. bgy. mybatis. bean. Employee ;
import com. bgy. mybatis. dao. EmployeeMapper ;
import com. bgy. mybatis. dao. EmployeeMapperAnnotation ;
class MybatisTest {
public SqlSessionFactory getSqlSessionFactory ( ) throws IOException {
String resource = "mybatis-config.xml" ;
InputStream inputStream = Resources . getResourceAsStream ( resource) ;
return new SqlSessionFactoryBuilder ( ) . build ( inputStream) ;
}
@Test
public void test02 ( ) throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory ( ) ;
SqlSession openSession = sqlSessionFactory. openSession ( ) ;
try {
EmployeeMapperAnnotation mapper = openSession. getMapper ( EmployeeMapperAnnotation . class ) ;
Employee employee = mapper. getEmpById ( 1 ) ;
System . out. println ( "test02" ) ;
System . out. println ( employee) ;
} finally {
openSession. close ( ) ;
}
}
@Test
public void test03 ( ) throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory ( ) ;
SqlSession sqlSession = sqlSessionFactory. openSession ( ) ;
try {
EmployeeMapper mapper = sqlSession. getMapper ( EmployeeMapper . class ) ;
Map < String , Object > map = new HashMap ( ) ;
map. put ( "id" , 1 ) ;
map. put ( "lastName" , "zhangsan" ) ;
Employee employee = mapper. getEmpByMap ( map) ;
System . out. println ( employee) ;
} finally {
sqlSession. close ( ) ;
}
}
}