1. 程式人生 > >Mybatis配置和基於配置的使用

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 id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
        //value:提供連線資料庫用的驅動
                <property name="driver" value="com.mysql.jdbc.Driver"/>
        //value:資料庫名稱
                <property name="url" value="jdbc:mysql://localhost:3306/blog"/>
                //value:資料庫賬號
        <property name="username" value="root"/>
        //value:資料庫密碼
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    //對映UserMapper.xml
    <mappers>
        <mapper resource="com/how2java/pojo/Category.xml"/>
    </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 id="selectUserById" resultType="User">
            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 id="addUser" parameterType="User">
        insert into user(uname,usex,upass) values (#{uname},#{usex},#{upass});
</insert>
呼叫方式:
User u = new User("張三","男",123456);
sqlSession .insert("com.blog.mapper.UserMapper.addUser", user);
//在對資料庫執行增加、修改、刪除操作時,需要進行commit和close,否則無法生效並耗費資源
sqlSession.commit();
sqlSession.close();

刪除:delete
<delete id="deleteUser">
        delete from user where uid = #{uid};
s</delete>

查詢:select
<select id="selectUserById" resultType="User">
        select * from user where uid = #{uid};  
</select>

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

查詢物件的集合:
<select id="selectAllUser" resultType="User">
    select * from user;
</select>
呼叫SqlSession物件的selectList("selectAllUser")方法

模糊查詢:
<select id="listUserByUnameId" resultType="User">
     select * from user where  uname like concat('%',#{uname},'%')
</select>

多條件查詢:例如分頁,可以使用parameterType="map",引數型別為map集合
<select id="listUserPage" parameterType="map" resultType="User">
      select * from user limit #{begin},#{size}
</select>
呼叫方法:
Map<String ,Object> map = new HashMap<>();
    map.put("begin", 0);
    map.put("size", 3);
List<User> list = sqlSession.selectList("listUserPage", map);

一對多查詢:collection、ofType
一個使用者可以發多個部落格,User類有個List<Blog> list屬性
<resultMap type="User" id="Userpojo">
        //子元素id代表resultMap的主鍵,而result代表其屬性。
        //id是作為唯一標識的,用在和其他物件例項對比時
    <id column="uid" property="uid"/>
    <result column="unick" property="unick"/>
        //property: 指的是User類中Blog集合的變數名, ofType:指的是集合中元素的型別
    <collection property="list" ofType="Blog">
            <id column="bid" property="bid"/>
            <result column="btitle" property="btitle"/>
    </collection>
</resultMap>
<select id="selectUserAndBlogs" resultMap="Userpojo">
       select unick,btitle from user inner join blog on buid=uid where uid=#{uid}
</select>

多對一查詢:association、javaType
多個部落格屬於一個使用者,Blog類有個User user屬性
<resultMap type="Blog" id="Blogpojo">
    <id column="bid" property="bid"/>
        <result column="btitle" property="btitle"/>
        //property: 指的是屬性名稱, javaType:指的是屬性的型別
        <association property="user" javaType="User">
            <id column="uid" property="uid"/>
            <result column="unick" property="unick"/>
        </association>
</resultMap>
<select id="selectBlogAndUser" resultMap="Blogpojo">
        select unick,btitle from blog inner join user on buid=uid 
</select>


多對多查詢:
一個使用者可以發多個部落格,User類有個List<Blog> listBlog屬性,Blog有評論集合List<Comment> clist
<resultMap type="User" id="userblogscomments">
        <id column="uid" property="uid"/>
        <result column="unick" property="unick"/>
        <collection property="list" ofType="Blog">
            <id column="bid" property="bid"/>
            <result column="btitle" property="btitle"/>
//在最內層的collection、association可以通過上層的結果集column,呼叫查詢語句select直接查詢
            <collection property="clist" column="bid" select="selectCommentss">
            </collection>
        </collection>
</resultMap>
<select id="selectUserss" resultMap="userblogscomments" parameterType="int">
        select * from user inner join blog on buid=uid  where uid=#{uid}
</select>
<select id="selectCommentss" parameterType="int" resultType="Comment">
        select * from comment where cbid=#{bid}
</select>