在 MyBatis 中,namespace
的包名要和 DAO/Mapper 接口的包名一致!
select
用于选择、查询语句:
id
:对应 namespace
中的方法名;resultType
:SQL 语句执行的返回值类型;parameterType
:参数类型。// 根据ID查询用户
User getUserById(int id);Copy to clipboardErrorCopied
<select id="getUserById" parameterType="int" resultType="com.oddfar.pojo.User">
select * from mybatis.user where id = #{id}
</select>Copy to clipboardErrorCopied
@Test
public void getUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}Copy to clipboardErrorCopied
<!-- 直接使用对象属性 -->
<insert id="addUser" parameterType="com.oddfar.pojo.User">
insert into mybatis.user (id, name, pwd) values (#{id},#{name},#{pwd});
</insert>Copy to clipboardErrorCopied
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(4, "zhiyuan", "212313"));
if (res > 0) {
// 提交事务
sqlSession.commit();
System.out.println("添加成功");
}
sqlSession.close();
}Copy to clipboardErrorCopied
<update id="updateUser" parameterType="com.oddfar.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id = #{id} ;
</update>Copy to clipboardErrorCopied
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id};
</delete>Copy to clipboardErrorCopied
注意点:
sqlSession.commit()
。resource
绑定 Mapper 时,需要使用路径。当实体类或数据库表字段过多时,可以考虑使用 Map 传递参数。
// 用Map插入数据
int addUser2(Map<String,Object> map);Copy to clipboardErrorCopied
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,name,pwd) values (#{userid},#{username},#{passWord});
</insert>Copy to clipboardErrorCopied
@Test
public void addUser2() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String, Object>();
map.put("userid",5);
map.put("passWord","2222333");
map.put("username","map");
int res = mapper.addUser2(map);
if (res > 0) {
// 提交事务
sqlSession.commit();
System.out.println("添加成功");
}
sqlSession.close();
}Copy to clipboardErrorCopied
如何进行模糊查询?
有两种方式:
%
。List<User> userList = mapper.getUserLike("%李%");Copy to clipboardErrorCopied
select * from mybatis.user where name like "%"#{value}"%"Copy to clipboardErrorCopied
推荐使用第二种方式。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有