mybatis06 增刪改差 源碼

user.java

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;}@Overridepublic String toString() {return "User [id=" + id + ", username=" + username + ", sex=" + sex+ ", birthday=" + birthday + ", address=" + address + "]";}}

uese.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">
<!-- namespace命名空間,為了分類管理sql語句,對sql語句進行隔離,方便管理 ,在后面采用mapper開發dao這種方式時使用namespace有特殊作用...
mapper代理開發時將namespace指定為mapper接口的全限定名-->
<mapper namespace="test">
<!-- 在mapper.xml文件中配置很多的sql語句,每個sql語句封裝為一個MappedStatement對象
mapper.xml(就是這里的User.xml)--><!-- 根據id查詢用戶信息 --><!-- id:唯一標識 一個statement#{}:表示 一個占位符(?也表示一個占位符),如果#{}中傳入簡單類型的參數,#{}中的名稱隨意parameterType:輸入 參數的類型,通過#{}接收parameterType輸入 的參數resultType:輸出結果 類型,不管返回是多條還是單條,指定單條的pojo類型--><select id="findUserById" parameterType="int" resultType="cn.itcast.mybatis.po.User">SELECT * FROM USER WHERE id= #{id}</select><!-- 根據用戶名稱查詢用戶信息,可能返回多條,模糊查詢,${}:表示sql的拼接,通過${}接收參數,將參數的內容不加任何修飾拼接在sql中。--><select id="findUserByName" parameterType="java.lang.String" resultType="cn.itcast.mybatis.po.User">select * from user where username like '%${value}%'</select><!-- 添加用戶parameterType:輸入 參數的類型,User對象 包括 username,birthday,sex,address#{}是占位符可以把字符串的日期類型自動轉換為Date類型#{}接收pojo數據,可以使用OGNL解析出pojo的屬性值(OGNL對象導航語言,struts2可以使用OGNL,如果username是一個對象,則可以用#{username.name})#{username}表示從parameterType中獲取pojo的屬性值需求:user對象插入到數據庫后,新記錄的主鍵要通過user對象返回,這樣就可以通過user獲取主鍵值。解決思路:通過LAST_INSERT_ID()函數獲取剛插入記錄的自增主鍵值,selectKey:用于進行主鍵返回,里面定義了獲取主鍵值的sql,在insert語句執行后,執行select LAST_INSERT_ID()就可以獲取自增主鍵。order:設置selectKey中sql執行的順序,相對于insert語句來說,AFTER就是在insert語句執行后執行select LAST_INSERT_ID()keyProperty:將主鍵值設置到User對象的哪個屬性,resultType:select LAST_INSERT_ID()的結果 類型,就是要插入User對象的id屬性的類型,如果User對象的id屬性是string則這里就是String。--><insert id="insertUser" parameterType="cn.itcast.mybatis.po.User"><selectKey keyProperty="id" order="AFTER" resultType="int">select LAST_INSERT_ID()    <!-- 這條語句可以直接在sqldevelop運行 --></selectKey>INSERT INTO USER(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address})</insert><!-- mysql的uuid生成主鍵 --><!-- <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User"><selectKey keyProperty="id" order="BEFORE" resultType="string">select uuid()               <!-- 這條語句可以直接在sqldevelop運行</selectKey>INSERT INTO USER(id,username,birthday,sex,address) VALUES(#{id},#{username},#{birthday},#{sex},#{address})</insert> --><!-- oracle在執行insert之前執行select 序列.nextval() from dual取出序列最大值((select 序列.nextval()得到oracle的序列值),將值設置到user對象 的id屬性--><!-- <insert id="insertUser" parameterType="cn.itcast.mybatis.po.User"><selectKey keyProperty="id" order="BEFORE" resultType="int">select 序列.nextval() from dual        <!-- 這條語句可以直接在sqldevelop運行 --></selectKey>INSERT INTO USER(id,username,birthday,sex,address) VALUES(#{id},#{username},#{birthday},#{sex},#{address})</insert> --><!-- 用戶刪除  --><delete id="deleteUser" parameterType="int">delete from user where id=#{id}</delete><!-- 用戶更新 要求:傳入的user對象中包括 id屬性值--><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

<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 屬性定義加載一個properties文件在 properties標簽 中配置屬性值--><properties resource="db.properties"><!-- <property name="" value=""/> --></properties><!-- 定義 別名 --><typeAliases><!--單個別名的定義alias:別名,type:別名映射的類型  --><!-- <typeAlias type="cn.itcast.mybatis.po.User" alias="user"/> --><!-- 批量別名定義指定包路徑,自動掃描包下邊的pojo,定義別名,別名默認為類名(首字母小寫或大寫)--><package name="cn.itcast.mybatis.po"/></typeAliases><!-- 和spring整合后 environments配置將廢除--><environments default="development"><environment id="development"><!-- 使用jdbc事務管理--><transactionManager type="JDBC" /><!-- 數據庫連接池--><dataSource type="POOLED"><!-- 數據庫連接參數 --><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><!--加載mapper映射如果將和spring整合后,可以使用整合包中提供的mapper掃描器,此處的mappers不用配置了。--><mappers><!-- resource是classpath,通過resource加載mapper的映射文件 --><mapper resource="sqlmap/User.xml" /><!-- <mapper resource="mapper/UserMapper.xml" /> --><!-- 通過class引用mapper接口 class:配置mapper接口全限定名要求:需要mapper.xml和mapper.java同名并且在一個目錄 中--><!-- <mapper class="cn.itcast.mybatis.mapper.UserMapper"/> --><!-- 批量mapper配置 通過package進行自動掃描包下邊的mapper接口,要求:需要mapper.xml和mapper.java同名并且在一個目錄 中--><package name="cn.itcast.mybatis.mapper"/></mappers></configuration>

Test.java

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        //before注解public void init() throws IOException {// 配置文件(SqlMapConfig.xml)String resource = "SqlMapConfig.xml";// 加載配置文件到輸入 流InputStream inputStream = Resources.getResourceAsStream(resource);// 創建會話工廠sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}// 測試根據id查詢用戶(得到單條記錄)
    @Testpublic void testFindUserById() {// 通過sqlSessionFactory創建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();// 通過sqlSession操作數據庫// 第一個參數:statement的位置,等于namespace+statement的id// 第二個參數:傳入的參數//返回userUser user = null;try {user = sqlSession.selectOne("test.findUserById", 2);} catch (Exception e) {e.printStackTrace();} finally {// 關閉sqlSession
            sqlSession.close();}System.out.println(user);}// 測試根據id查詢用戶(得到單條記錄)
    @Testpublic void testFindUserByName() {// 通過sqlSessionFactory創建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();// 通過sqlSession操作數據庫// 第一個參數:statement的位置,等于namespace+statement的id// 第二個參數:傳入的參數List<User> list = null;try {list = sqlSession.selectList("test.findUserByName", "小明");} catch (Exception e) {e.printStackTrace();} finally {// 關閉sqlSession
            sqlSession.close();}System.out.println(list.get(0).getUsername());}// 測試根據id查詢用戶(得到單條記錄)
    @Testpublic void testInsertUser() {// 通過sqlSessionFactory創建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();// 通過sqlSession操作數據庫// 創建插入數據對象User user = new User();user.setUsername("浪子燕青");user.setAddress("河南鄭州");user.setBirthday(new Date());user.setSex("1");try {sqlSession.insert("test.insertUser", user);// 因為沒有設置成自動提交,所以需要提交事務,以后與spring 自動整合之后通過spring管理這些類就自動提交了。//調試的時候把myeclips編譯好的控制臺打印的sql語句放入sqlserver軟件中進行手動調試
            sqlSession.commit();} catch (Exception e) {e.printStackTrace();} finally {// 關閉sqlSession
            sqlSession.close();}//打印主鍵,比如2個表關聯,把副表插入數據庫之后把外鍵插入主表中//不用<selectKey/>就沒有主鍵id返回(此時id為null),//需求:user對象插入到數據庫后,新記錄的主鍵要通過user對象返回,這樣就可以通過user獲取主鍵值。System.out.println("用戶的id=" + user.getId());}// 測試根據id刪除用戶(得到單條記錄)
    @Testpublic void testDeleteUser() {// 通過sqlSessionFactory創建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();// 通過sqlSession操作數據庫try {sqlSession.delete("test.deleteUser", 35);// 需要提交事務
            sqlSession.commit();} catch (Exception e) {e.printStackTrace();} finally {// 關閉sqlSession
            sqlSession.close();}}// 測試根據id更新用戶(得到單條記錄)
    @Testpublic void testUpdateUser() {// 通過sqlSessionFactory創建sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();// 通過sqlSession操作數據庫// 創建更新數據對象,要求必須包括 idUser user = new User();user.setId(35);user.setUsername("燕青");user.setAddress("河南鄭州");
//        user.setBirthday(new Date());user.setSex("1");try {sqlSession.update("test.updateUser", user);// 需要提交事務
            sqlSession.commit();} catch (Exception e) {e.printStackTrace();} finally {// 關閉sqlSession
            sqlSession.close();}System.out.println("用戶的id=" + user.getId());}}

?

轉載于:https://www.cnblogs.com/yaowen/p/4869265.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/375483.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/375483.shtml
英文地址,請注明出處:http://en.pswp.cn/news/375483.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

socket 編程 基于 select 實現的回射客戶端/服務程序

github 代碼 地址 unp.h #include <stdio.h> #include <unistd.h> #include <arpa/inet.h> #include <string.h> #include <sys/socket.h> #include <stdlib.h> #include <errno.h> #include <sys/wait.h> #include <sys…

MyEclipse的優化

出自&#xff1a;http://blog.csdn.net/u010124571/article/details/41316255?refmyread 第一步: 取消自動validation validation有一堆&#xff0c;什么xml、jsp、jsf、js等等&#xff0c;我們沒有必要全部都去自動校驗一下&#xff0c;只是需要的時候才會手工校驗一下&…

NSlog輸出

NSLog的定義 void NSLog(NSString *format, …); 基本上&#xff0c;NSLog很像printf&#xff0c;同樣會在console中輸出顯示結果。不同的是&#xff0c;傳遞進去的格式化字符是NSString的對象&#xff0c;而不是char *這種字符串指針。 實例 NSLog可以如下面的方法使用&#x…

推理題,會則秒解

你和你的朋友&#xff0c;兩個人一起玩 Nim 游戲&#xff1a;桌子上有一堆石頭&#xff0c;每次你們輪流拿掉 1 - 3 塊石頭。 拿掉最后一塊石頭的人就是獲勝者。你作為先手。 你們是聰明人&#xff0c;每一步都是最優解。 編寫一個函數&#xff0c;來判斷你是否可以在給定石頭…

【圖論】割點、橋、雙連通

連通分量 個數可以通過一次BFS或者DFS得到 割點和橋 可以枚舉刪除每一個點或者每一條邊&#xff0c;判斷連通分量個數是否增加 更好的方法 該算法是R.Tarjan發明的。對圖深度優先搜索&#xff0c;定義DFS(u)為u在搜索樹&#xff08;以下簡稱為樹&#xff09;中被遍歷到的次序號…

奇酷手機顯示Log

1、在桌面點擊撥號&#xff0c;在撥號盤輸入“*20121220#”&#xff0c;進入工程模式;2、看到日志輸出等級&#xff0c;點進去 Log print enable 選 enable Java log level 選 LOGV C and C log level 選 LOGV Kernel log level 選 KERN_DEBUG3、完畢 參考網址&#xff1a;http…

getCanonicalPath getAbsolutePath區別

1、在winows環境下它們的區別是 &#xfeff;&#xfeff;getCanonicalPath是標準路徑&#xff0c;沒有特殊字符&#xff0c;getAbsolutePath是有特殊字符的 2、在AIX系統中它們的區別&#xff1a; 首先編譯&#xff1a;javac com/ai/test/BugTest.java 然后運行&#xff1a;ja…

Hbase與hive整合

//hive與hbase整合create table lectrure.hbase_lecture10(sname string, score int) stored by org.apache.hadoop.hive.hbase.HBaseStorageHandler whth serdeproperties("hbase.columns.mapping" :key,cf1:score)tblproperties("hbase.table.name" &q…

C++實現一個http服務器

一個簡單的博客后端服務器 github地址&#xff0c;持續更新 設計參考 #define MYSQLPP_MYSQL_HEADERS_BURIED #include "httplib.h" #include "rapidjson/document.h" #include <mysql/mysql.h> #include <iostream> #include <string>…

KMP算法的java實現

package com.trs.utils;public class KMPStr {/** 在KMP算法中&#xff0c;最難求的就是next函數&#xff0c;如何理解next函數是一個難題&#xff0c;特別是knext[k]&#xff0c;這里* 需要指出的是當p[i]!p[j]時&#xff0c;我們只有通過回溯將k的值逐漸減小&#xff0c;貌似…

線段分割法實現微信搶紅包

無意間看到的一種實現搶紅包的方法&#xff0c;于是用C實現了一下。 將一個紅包分成 n 份 具體的思路是&#xff0c;將一個紅包看作是一個線段&#xff0c;線段的長就是紅包總金額&#xff0c;然后在這個線段上隨機切 n-1 刀&#xff0c;分成 n 份&#xff0c;然后搶紅包的人依…

JAVA多線程和并發基礎面試問答(轉載)

JAVA多線程和并發基礎面試問答 原文鏈接&#xff1a;http://ifeve.com/java-multi-threading-concurrency-interview-questions-with-answers/ 多線程和并發問題是Java技術面試中面試官比較喜歡問的問題之一。在這里&#xff0c;從面試的角度列出了大部分重要的問題&#xff0c…

Linux的學習--crontab

之前了解過一點crontab&#xff0c;前段時間比較閑&#xff0c;就熟悉了一下&#xff0c;今天總結記錄一下。 crontab命令常見于Unix和類Unix的操作系統之中&#xff0c;用于設置周期性被執行的指令。該命令從標準輸入設備讀取指令&#xff0c;并將其存放于"crontab"…

C++雪花算法實現

看來一下雪花算法的實現方法&#xff0c;用 c試著實現了一下&#xff0c;這里僅僅是實現了算法的流程&#xff0c;但是具體的細節&#xff0c;如并發、多線程訪問等等沒有具體考慮。 雪花算法的簡單講解參考 #include <sys/select.h> #include <iostream> #includ…

CAlayer層的屬性

iOS開發UI篇—CAlayer層的屬性 一、position和anchorPoint 1.簡單介紹 CALayer有2個非常重要的屬性&#xff1a;position和anchorPoint property CGPoint position; 用來設置CALayer在父層中的位置 以父層的左上角為原點(0, 0) property CGPoint anchorPoint; 稱為“定位點”、…

Window Linux下實現指定目錄內文件變更的監控方法

轉自&#xff1a;http://qbaok.blog.163.com/blog/static/10129265201112302014782/ 對于監控指定目錄內文件變更&#xff0c;window 系統提供了兩個未公開API&#xff1a;SHChangeNotifyRegister SHChangeNotifyDeregister 分別用于注冊Notify以及監視。 同時&#xff0c;還提…

Odoo9發行說明

2015年10月1日&#xff0c;期待已久的Odoo9正式發布。本文是Odoo9正式版發行說明&#xff0c;基于官網資料翻譯。 譯者: 蘇州-微塵原文地址&#xff1a;https://www.odoo.com/page/odoo-9-release-notes譯文地址&#xff1a;http://blog.csdn.net/wangnan537/article/details/4…

揭秘史上最完美一步到位的搭建Andoriod開發環境

Windows環境下Android開發環境搭建雖然不難而且網上資料眾多&#xff0c;但是眾多資料如出一折 忽略了很多細節&#xff0c;最終還是沒能達到滿意效果。 基本步驟如下&#xff1a;JDK安裝、環境變量配置、Eclipse下載、AndoriodSDK下載安裝、下載配置ADT但是到這里還不算完美搞…

基于OpenCv的人臉檢測、識別系統學習制作筆記之二

在網上找到了一個博客&#xff0c;里面有大量內容適合初學者接觸和了解人臉檢測的博文&#xff0c;正好符合我目前的學習方面&#xff0c;故將鏈接放上來&#xff0c;后續將分類原博客的博文并加上學習筆記。 傳送門&#xff1a; http://blog.sina.com.cn/s/articlelist_160256…

URL 化

URL化。編寫一種方法&#xff0c;將字符串中的空格全部替換為%20。假定該字符串尾部有足夠的空間存放新增字符&#xff0c;并且知道字符串的“真實”長度。&#xff08;注&#xff1a;用Java實現的話&#xff0c;請使用字符數組實現&#xff0c;以便直接在數組上操作。&#xf…