Java基礎-SSM之mybatis快速入門篇html
做者:尹正傑
java
版權聲明:原創做品,謝絕轉載!不然將追究法律責任。mysql
其實你可能會問什麼是SSM,簡單的說就是spring mvc + Spring + mybatis。本篇博客主要介紹mybatis的使用方法,配置起來相對簡單!mybatis是一種持久化技術,它內部封裝JDBC,將SQL語句外部化,換句話說,就是講SQL語句提早定義在文件中。官網文檔也是至關的友好:http://www.mybatis.org/mybatis-3/zh/getting-started.html(推薦使用谷歌瀏覽器打開)。spring
MyBatis 本是apache的一個開源項目iBatis, 2010年這個項目由apache software foundation 遷移到了google code,而且更名爲MyBatis 。MyBatis是一個基於Java的持久層框架。iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了幾乎全部的JDBC代碼和參數的手工設置以及結果集的檢索。MyBatis 使用簡單的 XML或註解用於配置和原始映射,將接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。sql
接下來咱們一塊兒體驗一下mybatis吧,使用它實現增刪改查操做,具體操做步驟以下:數據庫
1>.建立數據庫和表apache
1 create database yinzhengjie; 2 3 use yinzhengjie; 4 5 create table if not exists users(id int primary key auto_increment,name varchar(20) , age int) ;
2>.建立模塊引入Maven依賴瀏覽器
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>cn.org.yinzhengjie</groupId> 8 <artifactId>Mybatis</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 11 <dependencies> 12 <dependency> 13 <groupId>junit</groupId> 14 <artifactId>junit</artifactId> 15 <version>4.11</version> 16 </dependency> 17 <dependency> 18 <groupId>mysql</groupId> 19 <artifactId>mysql-connector-java</artifactId> 20 <version>5.1.17</version> 21 </dependency> 22 <dependency> 23 <groupId>org.mybatis</groupId> 24 <artifactId>mybatis</artifactId> 25 <version>3.2.1</version> 26 </dependency> 27 </dependencies> 28 29 </project>
3>.建立和表對應的java類session
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 7 package cn.org.yinzhengjie.mybatis.domain; 8 9 public class User { 10 private Integer id; 11 private String name; 12 private int age; 13 14 public Integer getId() { 15 return id; 16 } 17 18 public void setId(Integer id) { 19 this.id = id; 20 } 21 22 public String getName() { 23 return name; 24 } 25 26 public void setName(String name) { 27 this.name = name; 28 } 29 30 public int getAge() { 31 return age; 32 } 33 34 public void setAge(int age) { 35 this.age = age; 36 } 37 38 public String toString() { 39 return "User{" + "id=" + id + ", name='" + name + ", age=" + age + '}'; 40 } 41 }
4>.在項目resources目錄中建立映射UserMapper.xml文件mybatis
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 <!-- 定義名字空間,這個是自定義的,推薦定義爲和表名一致的!--> 5 <mapper namespace="users"> 6 <insert id="insert"> 7 insert into users(name, age) values(#{name}, #{age}) ; 8 </insert> 9 </mapper>
5>.建立鏈接數據庫的配置文件(注意,你的數據庫,用戶名,密碼可能跟我不一致,只須要修改相應的參數便可!)
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <properties> 7 <property name="driver" value="com.mysql.jdbc.Driver"/> 8 <property name="url" value="jdbc:mysql://localhost:5200/yinzhengjie"/> 9 <property name="username" value="root"/> 10 <property name="password" value="yinzhengjie"/> 11 </properties> 12 <environments default="development"> 13 <environment id="development"> 14 <transactionManager type="JDBC"/> 15 <dataSource type="POOLED"> 16 <property name="driver" value="${driver}"/> 17 <property name="url" value="${url}"/> 18 <property name="username" value="${username}"/> 19 <property name="password" value="${password}"/> 20 </dataSource> 21 </environment> 22 </environments> 23 <mappers> 24 <mapper resource="UserMapper.xml"/> 25 </mappers> 26 </configuration>
6>.編寫單元測試代碼,對數據庫插入一條數據
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.mybatis.test; 7 8 import cn.org.yinzhengjie.mybatis.domain.User.java.User; 9 import org.apache.ibatis.io.Resources; 10 import org.apache.ibatis.session.SqlSession; 11 import org.apache.ibatis.session.SqlSessionFactory; 12 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 13 import org.junit.Test; 14 15 import java.io.InputStream; 16 17 public class TestMybatis { 18 19 @Test 20 public void testInsert() throws Exception { 21 //加載配置文件,產生流對象 22 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); 23 //建立會話工廠 24 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in); 25 //開啓會話,開啓鏈接 26 SqlSession s = sf.openSession(); 27 28 User c = new User(); 29 c.setName("Yinzhengjie"); 30 c.setAge(18); 31 //注意。這裏的users就是UserMapper.xml的namespace(名稱空間),而insert則是id的值爲insert字符。 32 s.insert("users.insert", c); 33 //提交事務 34 s.commit(); 35 s.close(); 36 } 37 38 }
7>.查看測試表中的數據是否插入成功
8>.實現增刪改查操做
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 7 package cn.org.yinzhengjie.mybatis.domain; 8 9 public class User { 10 private Integer id; 11 private String name; 12 private int age; 13 14 public Integer getId() { 15 return id; 16 } 17 18 public void setId(Integer id) { 19 this.id = id; 20 } 21 22 public String getName() { 23 return name; 24 } 25 26 public void setName(String name) { 27 this.name = name; 28 } 29 30 public int getAge() { 31 return age; 32 } 33 34 public void setAge(int age) { 35 this.age = age; 36 } 37 38 public String toString() { 39 return "User{" + "id=" + id + ", name='" + name + ", age=" + age + '}'; 40 } 41 }
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4 <!-- 定義名字空間 --> 5 <mapper namespace="users"> 6 <insert id="insert"> 7 insert into users(name, age) values(#{name}, #{age}) ; 8 </insert> 9 10 <update id="update"> 11 update users set name = #{name} , age = #{age} where id = #{id} 12 </update> 13 14 <delete id="deleteOne"> 15 delete from users where id = #{id} 16 </delete> 17 18 <select id="selectOne" resultType="_User"> 19 select * from users where id = #{id} 20 </select> 21 22 <select id="selectAll" resultType="_User"> 23 select * from users 24 </select> 25 26 </mapper>
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <properties> 7 <property name="driver" value="com.mysql.jdbc.Driver"/> 8 <property name="url" value="jdbc:mysql://localhost:5200/yinzhengjie"/> 9 <property name="username" value="root"/> 10 <property name="password" value="yinzhengjie"/> 11 </properties> 12 13 <!-- 咱們使用typeAliases標籤給咱們自定義類起個別名。--> 14 <typeAliases> 15 <typeAlias type="cn.org.yinzhengjie.mybatis.domain.User" alias="_User" /> 16 </typeAliases> 17 18 <environments default="development"> 19 <environment id="development"> 20 <transactionManager type="JDBC"/> 21 <dataSource type="POOLED"> 22 <property name="driver" value="${driver}"/> 23 <property name="url" value="${url}"/> 24 <property name="username" value="${username}"/> 25 <property name="password" value="${password}"/> 26 </dataSource> 27 </environment> 28 </environments> 29 <mappers> 30 <mapper resource="UserMapper.xml"/> 31 </mappers> 32 </configuration>
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.mybatis.test; 7 8 import cn.org.yinzhengjie.mybatis.domain.User; 9 import org.apache.ibatis.io.Resources; 10 import org.apache.ibatis.session.SqlSession; 11 import org.apache.ibatis.session.SqlSessionFactory; 12 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 13 import org.junit.Test; 14 import java.io.InputStream; 15 import java.util.List; 16 17 public class TestMybatis { 18 19 @Test 20 public void testInsert(){ 21 SqlSession sess = null; 22 try { 23 //讀取配置文件 24 InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ; 25 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ; 26 //開啓會話(鏈接) 27 sess = sf.openSession(); 28 User u = new User(); 29 u.setName("Yinzhengjie"); 30 u.setAge(18); 31 //調用插入的方法 32 sess.insert("users.insert",u) ; 33 sess.commit(); 34 System.out.println("插入成功!"); 35 } catch (Exception e) { 36 sess.rollback(); 37 System.out.println("插入失敗!"); 38 e.printStackTrace(); 39 }finally { 40 sess.close(); 41 } 42 } 43 44 @Test 45 public void testUpdate(){ 46 SqlSession sess = null; 47 try { 48 //讀取配置文件 49 InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ; 50 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ; 51 //開啓會話(鏈接) 52 sess = sf.openSession(); 53 //定義須要修改的參數 54 User u = new User(); 55 u.setId(1); 56 u.setName("YINZHENGJIE"); 57 u.setAge(26); 58 //調用更新的方法,第一個參數須要指定標籤名稱,第二個參數傳入咱們定義好須要須要的對象 59 sess.update("users.update" , u) ; 60 //提交事物 61 sess.commit(); 62 System.out.println("更新成功!"); 63 } catch (Exception e) { 64 sess.rollback(); 65 System.out.println("更新失敗!"); 66 e.printStackTrace(); 67 }finally { 68 //釋放資源 69 sess.close(); 70 } 71 } 72 73 @Test 74 public void testDeleteOne(){ 75 SqlSession sess = null; 76 try { 77 //讀取配置文件 78 InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ; 79 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ; 80 //開啓會話(鏈接) 81 sess = sf.openSession(); 82 //調用刪除的方法 83 int res = sess.delete("users.deleteOne", 2); 84 if (res != 0){ 85 sess.commit(); 86 System.out.println("刪除成功!"); 87 }else { 88 System.out.println("指定的數據不存在,所以沒有刪除任何數據!"); 89 } 90 } catch (Exception e) { 91 sess.rollback(); 92 System.out.println("刪除失敗"); 93 e.printStackTrace(); 94 }finally { 95 sess.close(); 96 } 97 } 98 @Test 99 public void testSelectOne(){ 100 try { 101 //讀取配置文件 102 InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ; 103 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ; 104 //開啓會話(鏈接) 105 SqlSession sess = sf.openSession(); 106 //調用查詢的方法 107 User u = sess.selectOne("users.selectOne",1) ; 108 System.out.println(u.getName()); 109 sess.commit(); 110 sess.close(); 111 } catch (Exception e) { 112 System.out.println("您要查詢的條目不存在!"); 113 // e.printStackTrace(); 114 } 115 } 116 117 @Test 118 public void testSelectAll(){ 119 SqlSession sess = null; 120 try { 121 //讀取配置文件 122 InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ; 123 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ; 124 //開啓會話(鏈接) 125 sess = sf.openSession(); 126 //調用查詢的方法,返回的是一個List的結果集合 127 List<User> list = sess.selectList("users.selectAll") ; 128 for(User uu : list){ 129 System.out.println(uu.getName()); 130 } 131 sess.commit(); 132 133 } catch (Exception e) { 134 e.printStackTrace(); 135 }finally { 136 sess.close(); 137 } 138 } 139 }
文件存放目錄以下圖所示: