mybatis 传参数几种方式+模糊查询【vaynexiao】

传参方式1:将多个参数封装到一个map对象中,然后通过key取value

public interface UserDao {
    public List<User> selectUser(HashMap map) throws Exception;
}
    public void selectUser() throws Exception {

        SqlSession session = MybatisUtils.getSqlSession();
        
        UserDao mapper = session.getMapper(UserDao.class);
        HashMap<String,String> map = new HashMap<String, String>();
        map.put("abc","1");
        List<User> list = mapper.selectUser(map);
        
        for (User user: list){
            System.out.println(user);
        }
        session.close();
//You need either to explicitly disable SSL by setting useSSL=false
//这种错误原因是应该加上SSL
//value="jdbc:mysql://localhost:3306/study?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf-8"
    }
    <select id="selectUser" parameterType="map"  resultType="com.huawei.cpt.vo.User">
        select * from user where id = #{abc}
    </select>

传参方式2:从接口获取的参数多个,通过下标取值

public interface UserDao {
    public List<User> selectUser(String id, String name) throws Exception;
}
    <select id="selectUser" parameterType="com.xxx.xxx.vo.User"  resultType="com.xxx.xxx.vo.User">
        select * from user where id = #{0}
    </select>

传参方式3:注解来告诉xml取对应名字的参数

public interface UserDao {
    public List<User> selectUser(@Param("id") String id, @Param("name") String name) throws Exception;
}
    <select id="selectUser" parameterType="map"  resultType="com.huawei.cpt.vo.User">
        select * from user where id = #{id} and name = #{name}
    </select>

传参方式4:实体类,比如参数封装为User.java

public interface UserDao {
    public List<User> selectUser(User u) throws Exception;
}
    <select id="selectUser" parameterType="com.xxx.xxx.vo.User"  resultType="com.xxx.xxx.vo.User">
        select * from user where id = #{id} and name = #{name}
    </select>

拓展:方式4 paramType="com.xxx.xxx.vo.User" 传递的参数是vo实体类,和方式1 封装为一个map对象,甚至网上说的封装一个专门用来存参数的vo对象Condition.java,其实具体做法都类似。

模糊查询

第1种:在Java代码中添加sql通配符

string wildcardname = "%smi%";
list<name> names = mapper.selectlike(wildcardname);
 
<select id="selectlike">
 select * from foo where bar like #{value}
</select>

第2种:在sql语句中拼接通配符,会引起sql注入

string wildcardname = "smi";
list<name> names = mapper.selectlike(wildcardname);
 
<select id="selectlike">
     select * from foo where bar like "%"#{value}"%"
</select>
发布了49 篇原创文章 · 获赞 103 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/vayne_xiao/article/details/104866580