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>.创建数据库和表
create database yinzhengjie; use yinzhengjie; create table if not exists users(id int primary key auto_increment,name varchar(20) , age int) ;
2>.创建模块引入Maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>cn.org.yinzhengjie</groupId>
<artifactId>Mybatis</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.17</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.1</version>
</dependency>
</dependencies> </project>
3>.创建和表对应的java类
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.mybatis.domain; public class User {
private Integer id;
private String name;
private int age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String toString() {
return "User{" + "id=" + id + ", name='" + name + ", age=" + age + '}';
}
}
4>.在项目resources目录中创建映射UserMapper.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">
<!-- 定义名字空间,这个是自定义的,推荐定义为和表名一致的!-->
<mapper namespace="users">
<insert id="insert">
insert into users(name, age) values(#{name}, #{age}) ;
</insert>
</mapper>
5>.创建连接数据库的配置文件(注意,你的数据库,用户名,密码可能跟我不一致,只需要修改相应的参数即可!)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:5200/yinzhengjie"/>
<property name="username" value="root"/>
<property name="password" value="yinzhengjie"/>
</properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
6>.编写单元测试代码,对数据库插入一条数据
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.mybatis.test; import cn.org.yinzhengjie.mybatis.domain.User.java.User;
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 java.io.InputStream; public class TestMybatis { @Test
public void testInsert() throws Exception {
//加载配置文件,产生流对象
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//创建会话工厂
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in);
//开启会话,开启连接
SqlSession s = sf.openSession(); User c = new User();
c.setName("Yinzhengjie");
c.setAge(18);
//注意。这里的users就是UserMapper.xml的namespace(名称空间),而insert则是id的值为insert字符。
s.insert("users.insert", c);
//提交事务
s.commit();
s.close();
} }
7>.查看测试表中的数据是否插入成功
8>.实现增删改查操作
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/ package cn.org.yinzhengjie.mybatis.domain; public class User {
private Integer id;
private String name;
private int age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String toString() {
return "User{" + "id=" + id + ", name='" + name + ", age=" + age + '}';
}
}
User.java 文件内容
<?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">
<!-- 定义名字空间 -->
<mapper namespace="users">
<insert id="insert">
insert into users(name, age) values(#{name}, #{age}) ;
</insert> <update id="update">
update users set name = #{name} , age = #{age} where id = #{id}
</update> <delete id="deleteOne">
delete from users where id = #{id}
</delete> <select id="selectOne" resultType="_User">
select * from users where id = #{id}
</select> <select id="selectAll" resultType="_User">
select * from users
</select> </mapper>
UserMapper.xml 文件内容
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties>
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:5200/yinzhengjie"/>
<property name="username" value="root"/>
<property name="password" value="yinzhengjie"/>
</properties> <!-- 我们使用typeAliases标签给我们自定义类起个别名。-->
<typeAliases>
<typeAlias type="cn.org.yinzhengjie.mybatis.domain.User" alias="_User" />
</typeAliases> <environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
mybatis-config.xml 文件内容
/*
@author :yinzhengjie
Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/
EMAIL:y1053419035@qq.com
*/
package cn.org.yinzhengjie.mybatis.test; import cn.org.yinzhengjie.mybatis.domain.User;
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 java.io.InputStream;
import java.util.List; public class TestMybatis { @Test
public void testInsert(){
SqlSession sess = null;
try {
//读取配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ;
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ;
//开启会话(连接)
sess = sf.openSession();
User u = new User();
u.setName("Yinzhengjie");
u.setAge(18);
//调用插入的方法
sess.insert("users.insert",u) ;
sess.commit();
System.out.println("插入成功!");
} catch (Exception e) {
sess.rollback();
System.out.println("插入失败!");
e.printStackTrace();
}finally {
sess.close();
}
} @Test
public void testUpdate(){
SqlSession sess = null;
try {
//读取配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ;
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ;
//开启会话(连接)
sess = sf.openSession();
//定义需要修改的参数
User u = new User();
u.setId(1);
u.setName("YINZHENGJIE");
u.setAge(26);
//调用更新的方法,第一个参数需要指定标签名称,第二个参数传入我们定义好需要需要的对象
sess.update("users.update" , u) ;
//提交事物
sess.commit();
System.out.println("更新成功!");
} catch (Exception e) {
sess.rollback();
System.out.println("更新失败!");
e.printStackTrace();
}finally {
//释放资源
sess.close();
}
} @Test
public void testDeleteOne(){
SqlSession sess = null;
try {
//读取配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ;
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ;
//开启会话(连接)
sess = sf.openSession();
//调用删除的方法
int res = sess.delete("users.deleteOne", 2);
if (res != 0){
sess.commit();
System.out.println("删除成功!");
}else {
System.out.println("指定的数据不存在,因此没有删除任何数据!");
}
} catch (Exception e) {
sess.rollback();
System.out.println("删除失败");
e.printStackTrace();
}finally {
sess.close();
}
}
@Test
public void testSelectOne(){
try {
//读取配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ;
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ;
//开启会话(连接)
SqlSession sess = sf.openSession();
//调用查询的方法
User u = sess.selectOne("users.selectOne",1) ;
System.out.println(u.getName());
sess.commit();
sess.close();
} catch (Exception e) {
System.out.println("您要查询的条目不存在!");
// e.printStackTrace();
}
} @Test
public void testSelectAll(){
SqlSession sess = null;
try {
//读取配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml") ;
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(in) ;
//开启会话(连接)
sess = sf.openSession();
//调用查询的方法,返回的是一个List的结果集合
List<User> list = sess.selectList("users.selectAll") ;
for(User uu : list){
System.out.println(uu.getName());
}
sess.commit(); } catch (Exception e) {
e.printStackTrace();
}finally {
sess.close();
}
}
}
TestMybatis.java 文件内容
文件存放目录如下图所示: