java-mybaits-00103-入門程式原生的【查、增、刪、改】

來源:互聯網
上載者:User

標籤:cep   its   user   local   targe   nal   new   word   add   

一、需求實現以下功能:根據使用者id查詢一個使用者資訊根據使用者名稱稱模糊查詢使用者資訊列表添加使用者更新使用者刪除使用者二、具體步驟1.增加pom引用2.增加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
mybatis預設使用log4j作為輸出日誌資訊。3.SqlMapConfig.xml在classpath下建立SqlMapConfig.xml,如下:配置mybatis的運行環境,資料來源、事務等。
<?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交易管理 -->            <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>
View CodeSqlMapConfig.xml是mybatis核心設定檔,上邊檔案的配置內容為資料來源、交易管理。4、其他po類,mapper的編寫參看全部代碼 https://github.com/bjlhx15/mybatis三、總結知識點1.#{}和${} #{}  表示一個預留位置號,#{}接收輸入參數,類型可以是簡單類型,pojo、hashmap。  如果接收簡單類型,#{}中可以寫成value或其它名稱。  接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式擷取對象屬性值。 ${}  表示一個拼接符號,會引起sql注入,所以不建議使用${}。  接收輸入參數,類型可以是簡單類型,pojo、hashmap。  如果接收簡單類型,${}中只能寫成value。  接收pojo對象值,通過OGNL讀取對象中的屬性值,通過屬性.屬性.屬性...的方式擷取對象屬性值。2.parameterType和resultTypeparameterType:指定輸入參數類型,mybatis通過ognl從輸入對象中擷取參數值拼接在sql中。resultType:指定輸出結果類型,mybatis將sql查詢結果的一行記錄資料對應為resultType指定類型的對象。3.selectOne和selectListselectOne表示查詢出一條記錄進行映射。如果使用selectOne可以實現使用selectList也可以實現(list中只有一個對象)。selectList表示查詢出一個列表(多條記錄)進行映射。如果使用selectList查詢多條記錄,不能使用selectOne。 selectOne查詢一條記錄,如果使用selectOne查詢多條記錄則拋出異常:org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:70)4.mapper中的namespace  namespace :命名空間,用於隔離sql語句。  注意:使用 mapper代理方式開發,namespace比較重要5.sqlsession建立使用
// 設定檔String resource = "SqlMapConfig.xml";InputStream inputStream = Resources.getResourceAsStream(resource);// 使用SqlSessionFactoryBuilder從xml設定檔中建立SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession sqlSession = null;try {  // 建立資料庫會話執行個體sqlSession   sqlSession = sqlSessionFactory.openSession();   User user = sqlSession.selectOne("test.findUserById", 1);//執行sql   System.out.println(user);} catch (Exception e) {   e.printStackTrace();} finally {   if (sqlSession != null) {      sqlSession.close();   }}
6.mysql自增主鍵
<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User">       <!-- selectKey將主鍵返回,需要再返回 -->       <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>
添加selectKey實現將主鍵返回keyProperty:返回的主鍵儲存在pojo中的哪個屬性order:selectKey的執行順序,是相對與insert語句來說,由於mysql的自增原理執行完insert語句之後才將主鍵產生,所以這裡selectKey的執行順序為afterresultType:返回的主鍵是什麼類型LAST_INSERT_ID():是mysql的函數,返回auto_increment自增列新記錄id值。7.Mysql使用 uuid實現主鍵
<insert  id="insertUser" parameterType="cn.itcast.mybatis.po.User"><selectKey resultType="java.lang.String" order="BEFORE" keyProperty="id">  select uuid()</selectKey>  insert into user(id,username,birthday,sex,address)       values(#{id},#{username},#{birthday},#{sex},#{address})</insert>
注意這裡使用的order是“BEFORE” 使用mysql的uuid()函數產生主鍵,需要修改表中id欄位類型為string,長度設定成35位。  執行思路:先通過uuid()查詢到主鍵,將主鍵設定到user屬性中,進而輸入 到sql語句中。 執行uuid()語句順序相對於insert語句之前執行。8.Oracle使用序列產生主鍵首先自訂一個序列且用於產生主鍵,selectKey使用如下:
<insert  id="insertUser" parameterType="cn.itcast.mybatis.po.User"><selectKey resultType="java.lang.Integer" order="BEFORE" keyProperty="id">  SELECT 自訂序列.NEXTVAL FROM DUAL</selectKey>  insert into user(id,username,birthday,sex,address)       values(#{id},#{username},#{birthday},#{sex},#{address})</insert>
注意這裡使用的order是“BEFORE”    

java-mybaits-00103-入門程式原生的【查、增、刪、改】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.