Mybatis---增删改查
1.namespace
namespace中的包名要和 Dao/mapper接口的包名一致!
2.select
选择,查询语句;
- id:就是对应的namespace中的方法名;
- resultType:Sql语句的返回值!
- parameterType:参数类型!
2.1 编写接口
//根据ID查询用户
User getUserById(int id);
2.2 编写对应的mapper中的sql语句
<select id="getUserById" resultType="com.yang.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id}
</select>
2.3 测试
@Test
public void test1(){
SqlSession session = MybatisUtils.getSqlSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
session.close();
}
3.Insert
<insert id="addUser" parameterType="com.yang.pojo.User" >
insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
</insert>
4.update
<update id="updateUser" parameterType="com.yang.pojo.User" >
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
5.Delete
<delete id="DeleteUser" parameterType="int">
DELETE from mybatis.user where id=#{id};
</delete>
6.注意点
- 增删改需要提交事务!
- sqlSession.commit();是事务的提交,在查询中是没有的。
例子如下
@Test
public void test2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(5,"name","123456"));
sqlSession.commit();
sqlSession.close();
}