注意点:增删改需要提交事务
1.namespace
namespace中包名要和Dao/Mapper接口包名一致
2.select
查询语句;
编写接口
1
List<User> getAllUser();
编写对应mapper中的sql语句
1
2
3<select id="getAllUser" resultType="pojo.User">
select * from user
</select>测试
1
2
3
4
5
6
7
8
public void test() throws Exception{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
System.out.println(session.selectList("pojo.UserMapper.getAllUser"));
}
3.Insert
1 | <!--对象中的属性可以直接取出来--> |
4.Delete
1 | <delete id="deleteUser" parameterType="int"> |
5.Update
1 | <update id="updateUser" parameterType="pojo.User"> |
6.万能Map
假设我们的实体类或者数据库中的表,字段参数过多,我们应该考虑Map。
1 | //万能Map |
1 | <!--Map--> |
1 |
|
Map传递参数,直接在sql中取出key即可
对象传递参数,直接在sql取出对象属性即可
只有一个基本数据类型的情况下,可以直接在sql中取到
7.模糊查询
java代码执行的时候,传递通配符 % %
1
session.selectList("pojo.UserMapper.getUserLike","%李%")
在sql拼接中使用通配符!
1
select * from user where name like "%"#{value}"%"