0
点赞
收藏
分享

微信扫一扫

springboot 整合Mybatis传值的几种方式

方式一:直接传

接口

public interface UserMapper {
public List<User> getUserById(int id);
}

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.lxc.springboot.mapper.UserMapper" >
<select id="getUserById" resultType="com.lxc.springboot.domain.User">
select * from user where id = #{id}
</select>
</mapper>

方式二:通过注解方式 @Param

这种方式,在模糊查询的时候会用到,注解的参数和xml中的变量必须一致!(xml中不知道为什么必须要使用 ${} 方式,使用#{} 的方式查还不出来数据!)
接口

public interface UserMapper {
public List<User> getLikeList(@Param("name")String pname);
}

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.lxc.springboot.mapper.UserMapper" >

<select id="getLikeList" resultType="com.lxc.springboot.domain.User">
select id, user, name, age, password from user where name like '%${name}%'
</select>

</mapper>

方式三:通过Map键值对儿方式

这种方式的好处是变量(就是Map类型中的key)不需要跟字段名一致,而且传的字段根据实际需求来定,对于这个例子来说,如果使用 User类作为参数类型,那么你必须要传递所有的属性才行!

接口

import com.lxc.springboot.domain.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

public interface UserMapper {
// 插入数据
public void insertUser(Map<String, Object> user);
}

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.lxc.springboot.mapper.UserMapper" >

<insert id="insertUser" parameterType="hashmap">
insert into user(user, name, age, password) values (#{userPost}, #{userName}, #{userAge}, #{userPassword})
</insert>
</mapper>

就这么多,以后项目中用到别的方式,在记录!


举报

相关推荐

0 条评论