1.namespace
namespace中的包名要和Dao/Mapper接口的包名一致
2.select
选择,查询语句:
- id: namespace中的方法名
- resultType: sql语句的返回值
- parameterType: 参数类型
1.编写接口
//查询全部用户
List<User> getUserList();
2.编写对应的mapper中的sql语句
<select id="getUserList" resultType="com.hui.pojo.User">
select * from mybatis.user
</select>
3.测试
@Test
public void test(){
//1.获得sqlSession对象
SqlSession sqlSession = MybatisUtil.getSqlSession();
//2.执行sql
//方式1:getMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
//方式2:
//List<User> userList = sqlSession.selectList("com.hui.dao.UserMapper.getUserList");
for(User user:userList){
System.out.println(user.toString());
}
//关闭sqlSession
sqlSession.close();
}
注意!增删改需要提交事务
sqlSession.commit();
3.insert
<insert id="addUser" parameterType="com.hui.pojo.User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
4.update
<update id="updateUser" parameterType="com.hui.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>