Mybaits深入瞭解(二)—-入門實例

    

Mybatis CRUD實例


實例的開發環境

java環境 開發工具 數據庫
jdk1.7 myeclipse mysql

    

項目的目錄結構

這裏寫圖片描述
    

log4j.properties配置

    Log4j是Apache的一個開放源代碼項目,通過使用Log4j,我們可以控制日誌信息輸送的目的地是控制檯、文件、GUI組件、甚至是套接口服務器、NT的事件記錄器、UNIXSyslog守護進程等;我們也可以控制每一條日誌的輸出格式;通過定義每一條日誌信息的級別,我們能夠更加細緻地控制日誌的生成過程。最令人感興趣的就是,這些可以通過一個配置文件來靈活地進行配置,而不需要修改應用的代碼。 此外,通過Log4j其他語言接口,您可以在C、C++、.Net、PL/SQL程序中使用Log4j,其語法和用法與在Java程序中一樣,使得多語言 分佈式系統得到一個統一一致的日誌組件模塊。而且,通過使用各種第三方擴展,您可以很方便地將Log4j集成到J2EE、JINI甚至是SNMP應用中。想要詳細瞭解的話可以看看下面的博客:log4j.properties 詳解與配置步驟。在本項目中的配置:

# Global logging configuration
#在開發環境下日誌要設置成Debug,生產環境設置成info或error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

    

SqlMapConfig.xml的配置

    這是一個關鍵的配置文件,是mybaits的全局配置文件,不過名稱不固定,主要是用來配置數據源、事務等,mybaits的運行環境。

<?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>
    <!-- 和spring整合後 environments配置將廢除-->
    <environments default="development">
        <environment id="development">
        <!-- 使用jdbc事務管理-->
            <transactionManager type="JDBC" />
        <!-- 數據庫連接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8" />
                <property name="username" value="root" />
                <property name="password" value="root" />
            </dataSource>
        </environment>
    </environments>

    <!-- 加載映射文件 -->
    <mappers>
        <mapper resource="sqlmap/User.xml"/>
    </mappers>

</configuration>

    

創建POJO類

package cn.itcast.mybatis.po;

import java.util.Date;

public class User {
    private int id;
    private String username;// 用戶姓名
    private String sex;// 性別
    private Date birthday;// 生日
    private String address;// 地址
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", sex=" + sex
                + ", birthday=" + birthday + ", address=" + address + "]";
    }


}

    

映射文件

    映射文件的命名最好規範統一下,本實例中命名爲User.xml載映射文件中配置sql語句。

<?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">
<mapper namespace="test">

<!-- 根據id獲取用戶信息 -->
    <select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">
        select * from user where id = #{id}
    </select>
    <!-- 自定義條件查詢用戶列表 ,可能返回多條-->
    <select id="findUserByUsername" parameterType="java.lang.String" 
            resultType="cn.itcast.mybatis.po.User">
       select * from user where username like '%${value}%' 
    </select>

    <!-- 添加用戶 AFTER LAST_INSERT_ID() -->
    <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
        select LAST_INSERT_ID()
    </selectKey>
      insert into user(username,birthday,sex,address) 
      values(#{username},#{birthday},#{sex},#{address})
    </insert>

    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>

    <update id="updateUser" parameterType="cn.itcast.mybatis.po.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    </update>
</mapper>

    並在SqlMapConfig.xml文件中加載映射文件

<!-- 加載映射文件 -->
    <mappers>
        <mapper resource="sqlmap/User.xml"/>
    </mappers>

    

具體代碼實現

    接下來就是具體的代碼實現了,在MybatisFirst類中:

package cn.itcast.mybatis.first;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import cn.itcast.mybatis.po.User;

public class MybatisFirst {

    //創建會話工廠
    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void createSqlSessionFactory() throws IOException{
        //配置文件
        String resource="SqlMapConfig.xml";

        //得到配置文件流
        InputStream inputStream=Resources.getResourceAsStream(resource);
        // 使用SqlSessionFactoryBuilder從xml配置文件中創建SqlSessionFactory
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);

    }

    @Test
    public void findUserByIdTest() throws IOException{
        SqlSession sqlSession=null;

        try {
            //創建數據庫會話實例
            sqlSession=sqlSessionFactory.openSession();
            //根據用戶ID查詢單個記錄
            User user=sqlSession.selectOne("test.findUserById", 1);

            System.out.println(user);

        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }



    }

    @Test
    public void findUserByUsername() throws IOException{
        SqlSession sqlSession=null;

        try {
            //創建數據庫會話實例
            sqlSession=sqlSessionFactory.openSession();
            //根據用戶名查詢多條記錄
            List<User> list=sqlSession.selectList("test.findUserByUsername","張");
            System.out.println(list);
        } catch (Exception e) {

            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }

    }

    @Test
    public void testInsert(){
        SqlSession sqlSession=null;
        try {
            sqlSession=sqlSessionFactory.openSession();

            User user=new User();
            user.setAddress("廊坊市廣陽區");
            user.setBirthday(new Date());
            user.setSex("1");
            user.setUsername("張令");

            sqlSession.insert("test.insertUser",user);

            //提交事務
            sqlSession.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(sqlSession!=null){
                sqlSession.close();
            }
        }

    }


    @Test
    public void testDelete(){
        SqlSession sqlSession=null;
        try {
            sqlSession=sqlSessionFactory.openSession();

            sqlSession.delete("test.deleteUserById",29);

            //提交事務
            sqlSession.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(sqlSession!=null){
                sqlSession.close();
            }
        }
    }


    @Test
    public void testUpdate(){
        SqlSession sqlSession=null;
        try {
            sqlSession=sqlSessionFactory.openSession();



            User user=new User();
            user.setId(26);
            user.setAddress("河北省南宮市");
            user.setBirthday(new Date());
            user.setSex("男");
            user.setUsername("令仔");

            sqlSession.update("test.updateUser",user);
            //提交事務
            sqlSession.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(sqlSession!=null){
                sqlSession.close();
            }
        }
    }

}

    

    
    

    爲大家貢獻上我寫的源碼:Mybatis實例源碼下載地址

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章