Java基础-SSM之mybatis快速入门篇
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
其实你可能会问什么是SSM,简单的说就是spring mvc + Spring + mybatis。本篇博客主要介绍mybatis的使用方法,配置起来相对简单!mybatis是一种持久化技术,它内部封装JDBC,将SQL语句外部化,换句话说,就是讲SQL语句提前定义在文件中。官网文档也是相当的友好:http://www.mybatis.org/mybatis-3/zh/getting-started.html(推荐使用谷歌浏览器打开)。
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对象)映射成数据库中的记录。
接下来我们一起体验一下mybatis吧,使用它实现增删改查操作,具体操作步骤如下:
1>.创建数据库和表
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类
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文件
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 }
文件存放目录如下图所示: