第一节 前期准备
1.MyBatis版本3.4.5
2.创建Java项目
项目名称为:mybatis-demo1
3.添加依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
</dependency>
4.数据库sql
1.创建数据库
CREATE DATABASE mybatis_demo default character set utf8;
2.创建数据库测试表
CREATE TABLE user(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(100) NOT NULL COMMENT '用户名',
email VARCHAR(100) COMMENT '邮件地址',
age INT(11) COMMENT '性别',
gender tinyint(1) COMMENT '性别',
create_time timestamp NULL DEFAULT NULL COMMENT '创建时间',
update_time timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
)ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='用户表';
上面算是基本的准备工作都做完了,下面开始进行MyBatis的入门
第二节、MyBatis的官网地址:
http://www.mybatis.org/mybatis-3/zh/index.html
纯中文的官方文档让英文不好的同学更容易学习,不过我想要是基础不好的人,就算是中文的也不容易看懂。
第三节、MyBatis官网文档介绍
MyBatis官网提供了几种的入门方式,让入门更容易,纯中文的文档,更容易阅读,但是语言毕竟苍白无力,知识点不是非常的全面,所以要想学好MyBatis还需要不断的磨练,不断的根据你所想,进行测试,看是否能达到你想要的效果。
第四节、根据官网文档进行入门代码的编写
0.首先定义包路径
cn.im.domain 用于存放映射数据库的实体对象类
cn.im.mapper 用于存放映射数据库功能的接口
1.根据数据库user表创建映射数据库的实体对象类User
package cn.im.domain;
import java.util.Date;
/**
* Created by mybatis-demo
* Author: hushuang
* Date: 2017/11/9
* Time: 上午10:11
* Email: hd1611756908@163.com
* Description :创建映射数据库的实体对象
*/
public class User {
//用户ID
private Integer id;
//用户名称
private String username;
//用户邮箱
private String email;
//用户年龄
private int age;
//用户性别
private int gender;
//创建时间
private Date createTime;
//更新时间
private Date updateTime;
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", email='" + email + '\'' +
", age=" + age +
", gender=" + gender +
", createTime=" + createTime +
", updateTime=" + updateTime +
'}';
}
}
2.创建UserMapper接口并在内部定义操作数据库user表所需要的功能
package cn.im.mapper;
import cn.im.domain.User;
import java.util.List;
/**
* Created by mybatis-demo
* Author: hushuang
* Date: 2017/11/9
* Time: 上午10:45
* Email: hd1611756908@163.com
* Description : 创建操作数据库User表映射的接口类
*/
public interface UserMapper {
/**
* 添加一个用户
* @param user
* @return
* @throws Exception
*/
int addUser(User user) throws Exception;
/**
* 根据用户ID查询单个用户信息
* @param userId
* @return
* @throws Exception
*/
User findUserById(int userId) throws Exception;
/**
* 查询全部用户信息
* @return
* @throws Exception
*/
List<User> findUsers() throws Exception;
/**
* 更新用户信息
* @param user
* @return
* @throws Exception
*/
int updateUser(User user) throws Exception;
/**
* 根据用户ID删除用户信息
* @param userId
* @return
* @throws Exception
*/
int deleteUserById(int userId) throws Exception;
}
3.在resources文件夹下定义mapper文件夹用于存放映射数据库接口的xml文件
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="cn.im.mapper.UserMapper">
<!-- 添加一个用户 -->
<insert id="addUser" parameterType="cn.im.domain.User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user (username,email,age,gender,create_time,update_time) VALUES (#{username},#{email},#{age},#{gender},#{createTime},#{updateTime})
</insert>
<!-- 根据用户ID查询一个用户信息 -->
<select id="findUserById" resultType="cn.im.domain.User">
SELECT id,username,email,age,gender,create_time as createTime,update_time as updateTime FROM user WHERE id=#{id}
</select>
<!-- 查询全部用户信息 -->
<select id="findUsers" resultType="cn.im.domain.User">
SELECT id,username,email,age,gender,create_time as createTime,update_time as updateTime FROM user
</select>
<!-- 更新用户信息 -->
<update id="updateUser" parameterType="cn.im.domain.User">
UPDATE user
<set>
<if test="username!=null">username=#{username},</if>
<if test="email!=null">email=#{email},</if>
<if test="age!=0">age=#{age},</if>
<if test="gender!=0">gender=#{gender},</if>
<if test="createTime!=null">create_time=#{createTime},</if>
<if test="updateTime==null">update_time=now()</if>
</set>
WHERE id=#{id}
</update>
<!-- 删除用户 -->
<delete id="deleteUserById">
DELETE FROM user WHERE id=#{id}
</delete>
</mapper>
4.在resources文件夹下创建mybatis-config.xml配置文件
mybatis-config.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis_demo?useUnicode=true&useSSL=false&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
5.完成之后的项目结构如下
image.png简单介绍一下MyBatis操作数据库的步骤:
1.MyBatis操作数据库需要创建SqlSession对象
2.而SqlSession对象的创建需要从SqlSessionFactory对象中获取
3.SqlSessionFactory对象的创建需要SqlSessionFactoryBuilder对象加载mybatis-config.xml配置文件进行创建。
综上所述,我们反向推到结合官网说明很容易就可以进行数据库操作
1.首先通过Java的类加载器进行配置文件的加载
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
2.通过SqlSessionFactoryBuilder对象创建SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
通过以上步骤就可以很容易的获取到SqlSession对象,就可以对数据库进行操作了。
6.编写测试类
根据上面的项目结构图所示,在test目录的java文件夹下编写测试类UserTest和UserTest1这两个测试类是根据官网提供的不同方式进行入门的。
UserTest:
package cn.im;
import cn.im.domain.User;
import cn.im.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
/**
* Created by mybatis-demo
* Author: hushuang
* Date: 2017/11/9
* Time: 上午10:18
* Email: hd1611756908@163.com
* Description : 用户表的测试类,此测试类采用Mapper.class方式
*/
public class UserTest {
/**
* 日志logback
*/
private static final Logger LOG = LoggerFactory.getLogger(UserTest.class);
/**
* 测试连接数据库
*/
@Test
public void testConnection(){
//1.使用类加载器加载mybatis-config.xml文件或者采用官网提供的方法加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.打印数据库连接
LOG.info("数据库连接:====="+sqlSession.getConnection()+"");
}
/**
* 测试数据库的增删改查 ( CRUD )
*/
/*
插入一条用户信息
*/
@Test
public void testAddUser(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
/*
封装User对象参数
*/
User user = new User();
user.setUsername("韩梅梅");
user.setAge(18);
user.setGender(2);
user.setEmail("lilei@163.com");
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
try {
int i = userMapper.addUser(user);
LOG.info("影响行数i={}",i);
//提交 (注意如果不进行提交,数据库里面是没有数据的)
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {
sqlSession.close();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
查询一条用户信息
*/
@Test
public void testFindUserById(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
try {
User user = userMapper.findUserById(1000);
sqlSession.commit();
LOG.info("用户信息User={}",user);
} catch (Exception e) {
e.printStackTrace();
}finally {
sqlSession.close();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
查询全部用户信息
*/
@Test
public void testFindUsers(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
try {
List<User> users = userMapper.findUsers();
LOG.info("全部用户信息Users={}",users);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {
sqlSession.close();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
跟新用户信息
*/
@Test
public void testUpdateUser(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(1002);
user.setUsername("Polly");
try {
int i = userMapper.updateUser(user);
LOG.info("影响行数i={}",i);
sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}finally {
sqlSession.close();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
删除用户
*/
@Test
public void testDeleteUserById(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
try {
int i = userMapper.deleteUserById(1002);
sqlSession.commit();
LOG.info("影响行数i={}",i);
} catch (Exception e) {
e.printStackTrace();
}finally {
sqlSession.close();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
UserTest1类:
package cn.im;
import cn.im.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
/**
* Created by mybatis-demo
* Author: hushuang
* Date: 2017/11/9
* Time: 上午11:39
* Email: hd1611756908@163.com
* Description :采用userMapper.xml名称空间方式调用接口
*/
public class UserTest1 {
/**
* 日志logback
*/
private static final Logger LOG = LoggerFactory.getLogger(UserTest1.class);
/**
* 根据ID 删除用户信息
*/
@Test
public void testDeleteUserById(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
int i = sqlSession.delete("cn.im.mapper.UserMapper.deleteUserById", 1006);
//提交
sqlSession.commit();
LOG.info("影响行数i={}",i);
}
/**
* 更新用户信息
*/
@Test
public void testUpdateUser(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(1000);
user.setUsername("Tom");
user.setAge(18);
user.setGender(1);
user.setEmail("tom@163.com");
int i = sqlSession.update("cn.im.mapper.UserMapper.updateUser", user);
//提交
sqlSession.commit();
LOG.info("影响行数i={}",i);
}
/**
* 添加用户
*/
@Test
public void testAddUser(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setUsername("Jim");
user.setAge(18);
user.setGender(1);
user.setEmail("jim@163.com");
user.setCreateTime(new Date());
user.setUpdateTime(new Date());
int i = sqlSession.insert("cn.im.mapper.UserMapper.addUser", user);
//提交
sqlSession.commit();
LOG.info("影响行数i={}",i);
}
/**
* 查询全部用户
*/
@Test
public void testFindUsers(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> users = sqlSession.selectList("cn.im.mapper.UserMapper.findUsers");
LOG.info("用户列表users={}",users);
}
/**
* 通过用户ID查询用户信息
*/
@Test
public void testFindUserById(){
//1.加载配置文件
InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
//2.创建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3.从sqlSessionFactory获取sqlSession会话
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("cn.im.mapper.UserMapper.findUserById",1004);
//提交
sqlSession.commit();
LOG.info("用户信息User={}",user);
sqlSession.close();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上两种测试方式都只是针对于入门MyBatis,一种采用UserMapper.class方式查询UserMapper.java接口,一种是采用名称空间的方式直接查询UserMapper.xml映射文件.
以上为MyBatis的入门 CRUD 写的比较粗糙,可能会有个别错误的情况欢迎指正,如果有什么不明白可以相互交流,在下方评论。
代码已经上传到github
git clone https://github.com/hd1611756908/mybatis-demo.git
网友评论