Mybatis配置和基于配置的使用

导入jre包后还需要配置xml文件

配置文件mybatis-config.xml
在src目录下创建mybatis的主配置文件mybatis-config.xml 
内容:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    //自动扫描com.blog.bean下的类型,使得在后续配置文件UserMapper.xml中使用resultType的时候,可以直接使用类名(User),而不必写全com.blog.bena.User
    <typeAliases>
      <package name="com.blog.bean"/>
    </typeAliases>
    <environments default="development">
        <environment />
    </mappers>
</configuration>

在包com.blog.mapper下,新建文件UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    //表示命名空间是com.blog.mapper
    <mapper namespace="com.blog.mapper">
    //id: selectUserById 进行标示以供后续代码调用,resultType="User" 表示返回的数据和User关联起来,这里本应该使用的是 com.blog.bean.User, 但是因为上一步配置了别名,所以直接使用User就行了
        <select >
            select * from user where uid = #{uid};  
        </select>
    </mapper>

在java中调用:

//mybatis-config.xml文件路径:com.blog.config.mybatis-config.xml
String resource= "com/blog/config/mybatis-config.xml";
InputStream is = null;
try {
    is = Resources.getResourceAsStream(resource);
} catch (IOException e) {
    e.printStackTrace();
}
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
SqlSession sqlSession = ssf.getFactory().openSession();
//"com.blog.mapper.UserMapper.selectUserById"也可以写成"selectUserById",前提是多个配置文件下没有相同id
User u = (User)sqlSession .selectOne("selectUserById", 1);


添加:insert into
//parameterType参数类型为User类型
<insert , user);
//在对数据库执行增加、修改、删除操作时,需要进行commit和close,否则无法生效并耗费资源
sqlSession.commit();
sqlSession.close();

删除:delete
<delete >
        delete from user where uid = #{uid};
s</delete>

查询:select
<select >
        select * from user where uid = #{uid};  
</select>

修改:update
<update >
    update User set uname=#{uname} where uid=#{uid}    
</update>

查询对象的集合:
<select )方法

模糊查询:
<select >
     select * from user where  uname like concat('%',#{uname},'%')
</select>

多条件查询:例如分页,可以使用parameterType="map",参数类型为map集合
<select , map);

一对多查询:collection、ofType
一个用户可以发多个博客,User类有个List<Blog> list属性
<resultMap type="User" >
       select unick,btitle from user inner join blog on buid=uid where uid=#{uid}
</select>

多对一查询:association、javaType
多个博客属于一个用户,Blog类有个User user属性
<resultMap type="Blog" >
        select unick,btitle from blog inner join user on buid=uid 
</select>


多对多查询:
一个用户可以发多个博客,User类有个List<Blog> listBlog属性,Blog有评论集合List<Comment> clist
<resultMap type="User" >
        select * from comment where cbid=#{bid}
</select>