一、参数注解
遇到多个参数,因为不能因为两三个参数去创建新的JavaBean类,对于参数比较少的情况下可以使用@Param注解。
UserMapper.java
package tk.mybatis.simple.mapper; import org.apache.ibatis.annotations.Param; import tk.mybatis.simple.model.SysRole; import tk.mybatis.simple.model.SysUser; import java.util.List; /** * @author weihu * @date 2018/8/3/003 0:01 */ public interface UserMapper { /** * 根据用户id和角色的enabled状态获取用户的角色 */ List<SysRole> selectRolesByUserIdAndRoleEnabled(@Param("userId") Long userId,@Param("enabled") Integer enabled); }
UserMapper.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"> <!--sql语句映射文件--> <!--因为已经配置了别名,所以resultType可以直接写类名,没有配置的话就要写类全名--> <mapper namespace="tk.mybatis.simple.mapper.UserMapper"> <select id="selectRolesByUserIdAndRoleEnabled" resultType="tk.mybatis.simple.model.SysRole"> select r.id, r.role_name roleName, r.enabled, r.create_by createBy, r.create_time createTime from sys_user u inner join sys_user_role ur on u.id=ur.user_id inner join sys_role r on ur.role_id=r.id where u.id=#{userId} and r.enabled=#{enabled} </select> </mapper>
UserMapperTest.java
package tk.mybatis.simple.mapper; import org.apache.ibatis.session.SqlSession; import org.junit.Assert; import org.junit.Test; import tk.mybatis.simple.model.SysRole; import tk.mybatis.simple.model.SysUser; import java.util.Date; import java.util.List; /** * @author weihu * @date 2018/8/5/005 9:34 * @desc */ public class UserMapperTest extends BaseMapperTest { public void testParam(){ SqlSession sqlSession = getSqlSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<SysRole> sysRoles = userMapper.selectRolesByUserIdAndRoleEnabled(1L, 1); System.out.println(sysRoles); } catch (Exception e) { e.printStackTrace(); } finally { sqlSession.close(); } } }
原文地址:https://www.cnblogs.com/weihu/p/9427633.html
时间: 2024-10-29 02:45:22