国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

MyBatis入門基礎(一)

2019-11-15 00:42:28
字體:
來源:轉載
供稿:網友
MyBatis入門基礎(一)一:對原生態JDBC問題的總結

  新項目要使用mybatis作為持久層框架,由于本人之前一直使用的Hibernate,對mybatis的用法實在欠缺,最近幾天計劃把mybatis學習一哈,特將學習筆記記錄于此,方便大家參考,也方便自己查閱。

  話不多說,先看看原始的JDBC程序代碼,看看這樣的代碼存在什么問題。

package com.utils;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PReparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/** * @ClassName: JdbcTest * @Description: TODO(原始的JDBC操作數據庫) * @author warcaft * @date 2015-6-27 下午3:31:22 *  */public class JdbcTest {    public static void main(String[] args) {        // 數據庫連接        Connection connection = null;        // 預編譯的Statement,使用預編譯的Statement提高數據庫性能        PreparedStatement preparedStatement = null;        // 結果 集        ResultSet resultSet = null;        try {            // 加載數據庫驅動            Class.forName("com.MySQL.jdbc.Driver");            // 通過驅動管理類獲取數據庫鏈接            connection = DriverManager                    .getConnection(                            "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8",                            "root", "root");            // 定義sql語句 ?表示占位符            String sql = "select * from t_user where username = ?";            // 獲取預處理statement            preparedStatement = connection.prepareStatement(sql);            // 設置參數,第一個參數為sql語句中參數的序號(從1開始),第二個參數為設置的參數值            preparedStatement.setString(1, "王五");            // 向數據庫發出sql執行查詢,查詢出結果集            resultSet = preparedStatement.executeQuery();            // 遍歷查詢結果集            while (resultSet.next()) {                System.out.println(resultSet.getString("id") + "  "                        + resultSet.getString("username"));            }        } catch (Exception e) {            e.printStackTrace();        } finally {            // 釋放資源            if (resultSet != null) {                try {                    resultSet.close();                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (preparedStatement != null) {                try {                    preparedStatement.close();                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }            if (connection != null) {                try {                    connection.close();                } catch (SQLException e) {                    // TODO Auto-generated catch block                    e.printStackTrace();                }            }        }    }}
View Code

上面代碼的問題總結:

1、數據庫連接,使用時就創建,不使用立即釋放,對數據庫進行頻繁連接開啟和關閉,造成數據庫資源浪費,影響數據庫性能。

解決方案:使用數據庫連接池管理數據庫連接。

2、將sql語句硬編碼到java代碼中,如果sql語句修改,需要重新編譯java代碼,不利于系統維護。

解決方案:將sql語句配置在xml配置文件中,即使sql變化,不需要對java代碼進行重新編譯。

3、向preparedStatement中設置參數,對占位符號位置和設置參數值,硬編碼在java代碼中,不利于系統維護。

解決方案:將sql語句及占位符號和參數全部配置在xml中。

4、從resutSet中遍歷結果集數據時,存在硬編碼,將獲取表的字段進行硬編碼,,不利于系統維護。

解決方案:將查詢的結果集,自動映射成java對象。

二:MyBatis框架

  1.MyBatis是什么?(下載地址:https://github.com/mybatis/mybatis-3/releases) 

  MyBatis本是apache的一個開源項目iBatis,2010年這個項目由apachesoftwarefoundation遷移到了googlecode,并且改名為MyBatis,實質上Mybatis對ibatis進行一些改進。

  MyBatis是一個優秀的持久層框架,它對jdbc的操作數據庫的過程進行封裝,使開發者只需要關注SQL本身,而不需要花費精力去處理例如注冊驅動、創建connection、創建statement、手動設置參數、結果集檢索等jdbc繁雜的過程代碼。

  Mybatis通過xml或注解的方式將要執行的各種statement(statement、preparedStatemnt、CallableStatement)配置起來,并通過java對象和statement中的sql進行映射生成最終執行的sql語句,最后由mybatis框架執行sql并將結果映射成java對象并返回。

  2.MyBatis架構圖

  

1、mybatis配置

SqlMapConfig.xml,此文件作為mybatis的全局配置文件,配置了mybatis的運行環境等信息。

mapper.xml文件即sql映射文件,文件中配置了操作數據庫的sql語句。此文件需要在SqlMapConfig.xml中加載。

2、通過mybatis環境等配置信息構造SqlsessionFactory即會話工廠

3、由會話工廠創建sqlSession即會話,操作數據庫需要通過sqlSession進行。

4、mybatis底層自定義了Executor執行器接口操作數據庫,Executor接口有兩個實現,一個是基本執行器、一個是緩存執行器。

5、MappedStatement也是mybatis一個底層封裝對象,它包裝了mybatis配置信息及sql映射信息等。mapper.xml文件中一個sql對應一個MappedStatement對象,sql的id即是Mappedstatement的id。

6、MappedStatement對sql執行輸入參數進行定義,包括HashMap、基本類型、pojo,Executor通過MappedStatement在執行sql前將輸入的java對象映射至sql中,輸入參數映射就是jdbc編程中對preparedStatement設置參數。

7、MappedStatement對sql執行輸出結果進行定義,包括HashMap、基本類型、pojo,Executor通過MappedStatement在執行sql后將輸出結果映射至java對象中,輸出結果映射過程相當于jdbc編程中對結果的解析處理過程。

三:mybatis入門程序

1.需求:(1).根據用戶id(主鍵)查詢用戶信息(2).根據用戶名稱模糊查詢用戶信息(3).添加用戶4).刪除用戶(5).更新用戶

2.環境:java環境:JDK1.7,eclipse,Mysql5.1

3.工程目錄結構

 

4.從mybatis的jar包結構可知mybatis用的是log4j記錄日志,所以log4j.properties文件內容如下:

# Global logging configuration#在開發的環境下,日志級別要設置成DEBUG,生產環境設置成info或errorlog4j.rootLogger=DEBUG, stdout# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

5.SqlMapConfig.xml的配置文件內容

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//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事務管理,事務控制由mybatis管理-->            <transactionManager type="JDBC" />        <!-- 數據庫連接池,由mybatis管理-->            <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>

6.實體User.java內容

package com.mybatis.entity;import java.util.Date;/** * @ClassName: User * @Description: TODO(用戶實體) * @author warcaft * @date 2015-6-27 下午1:56:02 *  */public class User {    // 屬性名稱和數據庫字段名稱保持一致    private Integer id;    // 姓名    private String username;    // 性別    private String sex;    // 地址    private String address;    // 生日    private Date birthday;    public Integer getId() {        return id;    }    public void setId(Integer 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 String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    public Date getBirthday() {        return birthday;    }    public void setBirthday(Date birthday) {        this.birthday = birthday;    }    @Override    public String toString() {        return "User [id=" + id + ", username=" + username + ", sex=" + sex                + ", address=" + address + ", birthday=" + birthday + "]";    }}
View Code

7.映射文件User.xml的內容

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- namespace命名空間,作用就是對sql進行分類化的管理,理解為sql隔離    注意:使用mapper代理開發時,namespace有特殊作用 --><mapper namespace="test"><!-- 在映射文件中配置很多sql語句 --><!-- 需求:通過Id查詢用戶表的記錄 --><!-- 通過SELECT執行數據庫查詢     id:標識映射文件中的sql,稱為statement的id;        將sql語句封裝在mapperStatement的對象中,所以Id稱為Statement的id;    parameterType:指定輸入參數的類型,這里指定int型    #{}:表示一個占位符;    #{id}:其中Id表示接收輸入的參數,參數名稱就是Id,如果輸入參數是簡單類型,#{}中的參數名可以任意,可以是value或者其它名稱;    resultType:指定sql輸出結果所映射的java對象類型,select指定resultType表示將單條記錄映射成java對象。--><select id="findUserById" parameterType="int" resultType="com.mybatis.entity.User" >    select * from t_user where id=#{id}</select><!-- 根據用戶名稱模糊查詢用戶信息,可能返回多條數據    resultType:指定的就是單條記錄所映射的java類型;    ${}:表示拼接sql字符串,將接收到的參數內容不加任何修飾拼接在sql中.    使用${}拼接sql,可能會引起sql注入    ${value}:接收輸入參數的內容,如果傳入的是簡單類型,${}中只能使用value --><select id="findUserByName" parameterType="java.lang.String" resultType="com.mybatis.entity.User" >    select * from t_user where username LIKE '%${value}%'</select><!-- 添加用戶 parameterType:指定輸入的參數類型是pojo(包括用戶信息);#{}中指定pojo的屬性名稱,接收到pojo對象的屬性值    ,mybatis通過OGNL(類似struts2的OGNL)獲取對象的屬性值--><insert id="insertUser" parameterType="com.mybatis.entity.User" >    <!--         將insert插入的數據的主鍵返回到User對象中;        select last_insert_id():得到剛insert進去記錄的主鍵值,只適用于自增主鍵;        keyProperty:將查詢到的主鍵值,設置到parameterType指定的對象的那個屬性        order:select last_insert_id()執行順序,相對于insert語句來說它的執行順序。        resultType:指定select last_insert_id()的結果類型;     -->    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">        select last_insert_id()    </selectKey>    <!--         使用mysql的uuid(),實現非自增主鍵的返回。        執行過程:通過uuid()得到主鍵,將主鍵設置到user對象的Id的屬性中,其次,在insert執行時,從user對象中取出Id屬性值;     <selectKey keyProperty="id" order="BEFORE" resultType="java.lang.String">        select uuid()    </selectKey>        insert into t_user (id,username,birthday,sex,address) values(#{id},#{username},#{birthday},#{sex},#{address})     -->    insert into t_user (username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})</insert><!-- 刪除用戶     根據ID刪除用戶,需要輸入Id值-->    <delete id="deleteUser" parameterType="java.lang.Integer">        delete from t_user where id=#{id}    </delete><!-- 更新用戶     需要傳入用戶的Id和用戶的更新信息    parameterType:指定User對象,包括Id和用戶的更新信息,注意:Id是必須存在的    #{id}:從輸入的User對象中獲取Id的屬性值--><update id="updateUser" parameterType="com.mybatis.entity.User">    update t_user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address}     where id=#{id}</update></mapper>

8.測試程序MybatisService.java代碼

package com.mybatis.service;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.Test;import com.mybatis.entity.User;/** * @ClassName: MybatisService * @Description: TODO(mybatis入門程序) * @author warcaft * @date 2015-6-27 下午4:49:49 *  */public class MybatisService {    // 根據Id查詢用戶信息,得到一條記錄結果    @Test    public void findUserByIdTest() {        // mybatis的配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = null;        SqlSession sqlSession = null;        try {            inputStream = Resources.getResourceAsStream(resource);            // 1.創建會話工場,傳入mybatis的配置文件信息            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                    .build(inputStream);            // 2.通過工廠得到SqlSession            sqlSession = sqlSessionFactory.openSession();            // 3.通過sqlSession操作數據庫            // 第一個參數:映射文件中的statement的Id,等于namespace + "." + statement的id;            // 第二個參數:指定和映射文件中所匹配的parameterType類型的參數;            // sqlSession.selectOne結果是與映射文件所匹配的resultType類型的對象;            // selectOne:查詢一條結果            User user = sqlSession.selectOne("test.findUserById", 1);            System.out.println(user.toString());        } catch (IOException e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }            if (inputStream != null) {                try {                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    // 根據姓名模糊查詢用戶信息,得到一條或多條記錄結果    @Test    public void findUserByNameTest() {        // mybatis的配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = null;        SqlSession sqlSession = null;        try {            inputStream = Resources.getResourceAsStream(resource);            // 1.創建會話工場,傳入mybatis的配置文件信息            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                    .build(inputStream);            // 2.通過工廠得到SqlSession            sqlSession = sqlSessionFactory.openSession();            // 3.通過sqlSession操作數據庫            // 第一個參數:映射文件中的statement的Id,等于namespace + "." + statement的id;            // 第二個參數:指定和映射文件中所匹配的parameterType類型的參數;            // sqlSession.selectOne結果是與映射文件所匹配的resultType類型的對象;            // list中的user和resultType類型一致            List<User> list = sqlSession.selectList("test.findUserByName", "小");            System.out.println(list);        } catch (IOException e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }            if (inputStream != null) {                try {                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    // 添加用戶    @Test    public void insertUserTest() {        // mybatis的配置文件        String resource = "SqlMapConfig.xml";        InputStream inputStream = null;        SqlSession sqlSession = null;        try {            inputStream = Resources.getResourceAsStream(resource);            // 1.創建會話工場,傳入mybatis的配置文件信息            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                    .build(inputStream);            // 2.通過工廠得到SqlSession            sqlSession = sqlSessionFactory.openSession();            //插入用戶的對象            User user = new User();            user.setUsername("小紅");            user.setBirthday(new Date());            user.setSex("1");            user.setAddress("上海");            // 3.通過sqlSession操作數據庫            // 第一個參數:映射文件中的statement的Id,等于namespace + "." + statement的id;            // 第二個參數:指定和映射文件中所匹配的parameterType類型的參數;            // sqlSession.selectOne結果是與映射文件所匹配的resultType類型的對象;            sqlSession.insert("test.insertUser", user);            //執行提交事務            sqlSession.commit();                        //項目中經常需要 獲取新增的用戶的主鍵            System.out.println(user.getId());        } catch (IOException e) {            e.printStackTrace();        } finally {            if (sqlSession != null) {                sqlSession.close();            }            if (inputStream != null) {                try {                    inputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }        // 根據Id刪除用戶        @Test        public void deleteUserTest() {            // mybatis的配置文件            String resource = "SqlMapConfig.xml";            InputStream inputStream = null;            SqlSession sqlSession = null;            try {                inputStream = Resources.getResourceAsStream(resource);                // 1.創建會話工場,傳入mybatis的配置文件信息                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                        .build(inputStream);                // 2.通過工廠得到SqlSession                sqlSession = sqlSessionFactory.openSession();                // 3.通過sqlSession操作數據庫                // 第一個參數:映射文件中的statement的Id,等于namespace + "." + statement的id;                // 第二個參數:指定和映射文件中所匹配的parameterType類型的參數;                // sqlSession.selectOne結果是與映射文件所匹配的resultType類型的對象;                //傳入Id,刪除用戶                sqlSession.delete("test.deleteUser", 7);                //執行提交事務                sqlSession.commit();            } catch (IOException e) {                e.printStackTrace();            } finally {                if (sqlSession != null) {                    sqlSession.close();                }                if (inputStream != null) {                    try {                        inputStream.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }        }                // 根據Id更新用戶信息        @Test        public void updateUserTest() {            // mybatis的配置文件            String resource = "SqlMapConfig.xml";            InputStream inputStream = null;            SqlSession sqlSession = null;            try {                inputStream = Resources.getResourceAsStream(resource);                // 1.創建會話工場,傳入mybatis的配置文件信息                SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()                        .build(inputStream);                // 2.通過工廠得到SqlSession                sqlSession = sqlSessionFactory.openSession();                //更新用戶的信息                User user = new User();                user.setId(2);                user.setUsername("小黑");                user.setBirthday(new Date());                user.setSex("2");                user.setAddress("上海");                // 3.通過sqlSession操作數據庫                // 第一個參數:映射文件中的statement的Id,等于namespace + "." + statement的id;                // 第二個參數:指定和映射文件中所匹配的parameterType類型的參數;                // sqlSession.selectOne結果是與映射文件所匹配的resultType類型的對象;                //更具Id更新用戶                sqlSession.update("test.updateUser", user);                //執行提交事務                sqlSession.commit();            } catch (IOException e) {                e.printStackTrace();            } finally {                if (sqlSession != null) {                    sqlSession.close();                }                if (inputStream != null) {                    try {                        inputStream.close();                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }        }}

9.數據庫所用sql腳本

CREATE TABLE t_user (  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,  username VARCHAR(30) NOT NULL COMMENT '用戶名稱',  birthday DATE DEFAULT NULL COMMENT '生日',  sex CHAR(2) DEFAULT NULL COMMENT '性別',  address VARCHAR(256) DEFAULT NULL COMMENT '地址');INSERT INTO t_user (username,birthday,sex,address)                                VALUES                   ('小A','2015-06-27','2','北京'),                   ('小B','2015-06-27','2','北京'),                   ('小C','2015-06-27','1','北京'),                   ('小D','2015-06-27','2','北京');
四:mybatis和Hibernate的本質區別與應用場景

hibernate:是一個標準ORM框架(對象關系映射),入門門檻較高的,不需要程序寫sql,sql語句自動生成了,對sql語句進行優化、修改比較困難的。

應用場景:

適用與需求變化不多的中小型項目,比如:后臺管理系統,erp、orm、oa。。

mybatis:專注是sql本身,需要程序員自己編寫sql語句,sql修改、優化比較方便。mybatis是一個不完全的ORM框架,雖然程序員自己寫sql,mybatis也可以實現映射(輸入映射、輸出映射)。

應用場景:

適用與需求變化較多的項目,比如:互聯網項目。

五:小結

1.parameterType和resultType

  parameterType:在映射文件中通過parameterType指定輸入參數的類型。

  resultType:在映射文件中通過resultType指定輸出結果的類型

2.#{}和${}

#{}表示一個占位符號,#{}接收輸入參數,類型可以是簡單類型,pojo、hashmap;

如果接收簡單類型,#{}中可以寫成value或其它名稱;

#{}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式獲取對象屬性值。

${}表示一個拼接符號,會引用sql注入,所以不建議使用${};

${}接收輸入參數,類型可以是簡單類型,pojo、hashmap;

如果接收簡單類型,${}中只能寫成value;

${}接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式獲取對象屬性值。

3.selectOne()和selectList()

  selectOne表示查詢出一條記錄進行映射。如果使用selectOne可以實現使用selectList也可以實現(list中只有一個對象)。

  selectList表示查詢出一個列表(多條記錄)進行映射。如果使用selectList查詢多條記錄,不能使用selectOne。

  如果使用selectOne報錯: org.apache.ibatis.exceptions.TooManyResultsException:Expectedoneresult(ornull)tobereturnedbyselectOne(),butfound:4


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 治县。| 当雄县| 新和县| 高密市| 德兴市| 澄江县| 建平县| 大安市| 青铜峡市| 铜川市| 银川市| 夹江县| 临猗县| 景东| 正宁县| 东至县| 会同县| 昌图县| 安阳市| 玛沁县| 德令哈市| 高阳县| 双城市| 合阳县| 太白县| 浏阳市| 涟水县| 内丘县| 房产| 云南省| 博爱县| 大宁县| 杂多县| 东港市| 沾益县| 水富县| 衡东县| 拉萨市| 霍城县| 紫云| 久治县|