1.namespace
namespace中的包名要和Dao/Mapper接口的包名一致!
2.select
选择,查询语句;
- id:就是对应的namespace中的方法名;
- resultType:Sql语句执行的返回值!
- parameterType:参数类型!
1.编写接口
//根据id查询用户
User getUserById(int id);
2.编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
select * from mybatis.user where id = #{id}
</select>
3.测试
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
//关闭SqlSession
sqlSession.close();
}
3.Insert
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
4.update
<update id="updateUser" parameterType="com.kuang.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>
- 注意!增删改需要提交事务!
也可以在工具类utils设置自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}