常用的有三种方法:
-
通过封装一个对象,把参数用一个对象封装起来,保证类里有构造函数,在mapper接口里传对象,在mapper.xml里parameterType里传入对象类
public Student(Integer SID, String sname, String ssex, Integer sage) {
this.SID = SID;
Sname = sname;
Ssex = ssex;
Sage = sage;
}
----------------------------------------------------------------------
public int insertStudent(Student student);
----------------------------------------------------------------------
<insert id="insertStudent" parameterType="com.tulun.maventest.pojo.Student" >
insert into student(SID, Sname, Sage, Ssex) values (#{SID}, #{Sname} ,#{Sage}, #{Ssex} )
</insert> -
通过Map进行传参,将参数放到HashMap里,传一个Map对象,通过键值对的形式获取
Map<String,String> map=new HashMap<String,String>(); map.put("sid","4"); map.put("sname","刘能"); System.out.println(mapper.updateSnameById(map)); sqlSession.commit();// ----------------------------------------------------------------------- public int updateSnameById(Map map); ----------------------------------------------------------------------- <update id="updateSnameById" parameterType="Map" > update Student set sname = #{sname} where sid = #{sid} </update>
3. 基于注解(最简单),通过在mapper里方法参数前加上注解@Param(),mapper.xml里通过#{value}的方式取参,多参数就不能使用parameterType
public List<XXXBean> getXXXBeanList(@Param("id")String id, @Param("code")String code); ----------------------------------------------------------------------------------- <select id="getXXXBeanList" resultType="XXBean"> select t.* from tableName where id = #{id} and name = #{code} </select>如果参数里面需要传对象,使用@param(“xxx”)注解时,在mapper.xml里取参时必须加上xxx.属性名
public List<XXXBean> getXXXBeanList(@Param("id")String id, @Param("user")User user); ----------------------------------------------------------------------------------- <select id="getXXXBeanList" resultType="XXBean"> select t.* from tableName where id = #{user.id} and name = #{user.code} </select>
&&补充:在传入类型为int,且有可能为0的情况下,在对动态sql的参数进行判断的时候会将这个字段默认置空,所以需要去掉 user.status !=' ' 这个判断
public List<XXXbean> selectAll(@Param("user") User user);
-------------------------------------------------------------------------------------------------------------------------
<select id="selectAll" resultType="XXXbean">
select * from userTable<where>
<if test="user.status!=null">
and status = #{user.status}
</if>
<if test="user.name!=null and user.name!=' ' ">
and name= #{user.name}
</if>