引數傳遞
單個字面量型別的引數
在mapper介面中使用單個引數,直接使用#{}或者${}在對映檔案中接收,注意${}本質是字串拼接,因此在接收字元型的資料使用單引號括起來,#{}本質為佔位符.
eg:
mapper介面:
package com.mappers;
import com.pojo.User;
public interface UserMapper {
User selectUserById(int userid);
User selectUserByName(String username);
}
對映檔案:
<?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介面-->
<mapper namespace="com.mappers.UserMapper">
<!--第二個一致,對應方法名 User selectUserById(int userid); -->
<select id="selectUserById" resultType="user">
select * from user where userid=#{userid}
</select>
<!--User selectUserByName(String username);-->
<select id="selectUserByName" resultType="User">
select * from user where username='${username}'
</select>
<!-- select * from user where username=#{username}-->
</mapper>
呼叫方法時直接傳參:
selectUserByName("張三");
selectUserById(2);
介面方法引數有多個
這時系統會將引數放入Map集合中,以兩種方式進行儲存
- 以arg0,arg1....為鍵,傳入的引數為值
- 以param1,param2...為鍵,傳入的引數為值
因此在對映檔案中訪問可以透過#{}或者${}寫入對應鍵進行訪問
mapper介面:
package com.mappers;
import com.pojo.User;
public interface UserMapper {
User selectUserByIdAndName(int userid,String username);
}
對映檔案:
<!-- User selectUserByIdAndName(int userid,String username);-->
<select id="selectUserByIdAndName" resultType="User">
select * from user where userid=#{arg0} and username=#{arg1}
<!--或者 select * from user where userid=#{param1} and username=#{param2}-->
</select>
方式2:
使用map作為引數進行傳遞多個引數
mapper介面:
package com.mappers;
import com.pojo.User;
import java.util.Map;
public interface UserMapper {
User selectUserByIdAndName(Map<String, Object> map);
}
對映檔案:
<select id="selectUserByIdAndName" resultType="User">
select * from user where userid=#{userid} and username=#{username}
</select>
呼叫:先定義好map,再進行呼叫
Map<String,Object> map=new HashMap<>();
map.put("userid",2);
map.put("username","李四");
User user3=userMapper.selectUserByIdAndName(map);
方式3:(推薦)
使用@Param("")註解,本質也是放到Map集合裡,知識我們規定了鍵名,在使用時直接透過指定的鍵名訪問,在註解的引數裡寫入我們指定的鍵名
mapper介面:
package com.mappers;
import com.pojo.User;
public interface UserMapper {
User selectUserByIdAndName(@Param("userid") int userid, @Param("username") String username);
}
對映檔案:
<select id="selectUserByIdAndName" resultType="User">
select * from user where userid=#{userid} and username=#{username}
</select>
傳入引數為實體類物件
直接透過#{}或${}和屬性名對各個屬性值進行使用
mapper介面
package com.mappers;
import com.pojo.User;
public interface UserMapper {
int insertUser(User user);
}
對映檔案:使用時透過類內屬性名即可訪問
<!-- int insertUser(User user);-->
<insert id="insertUser">
insert into user values (null,#{username},#{userpass},#{usertel},#{usercard});
</insert>
呼叫:先定義,然後傳入使用
User user4=new User(1,"哈哈","aiw","159",10);
userMapper.insertUser(user4);