mybatis工作流程及基本CURD

mybatis的工作流程
  1. 通过Reader对象读取src目录下的mybatis.xml配置文件(该文本的位置和名字可任意)
  2. 通过SqlSessionFactoryBuilder对象创建SqlSessionFactory对象
  3. 从当前线程中获取SqlSession对象
  4. 事务开始
  5. 通过SqlSession对象读取StudentMapper.xml映射文件中的操作编号,从而读取sql语句
  6. 事务提交,必写
  7. 关闭SqlSession对象,并且分开当前线程与SqlSession对象,让GC尽早回收

接下来以user对象为例子,看看如何利用mybatis实现单表的增删改查

在resources目录下增加文件
db.propreties(连接数据库所需参数配置文件)
log4j.properties(日志配置文件),
mybatis.xml(mybatis核心配置文件,设置数据库连接和加载实体映射文件)

image.png

db.properties

mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/mybatis
mysql.username=root
mysql.password=123456


log4j.properties

log4j.rootLogger=debug,stdout,logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

mybatis.xml



 
    
    

    
    
    
    
    
    
    
        
        
            
            
            
            
                
                
                
                
                
            
        
        
    
    
    
    

    
    

java目录下新建三个包
com.lianwei.dao
com.lianwei.entity
com.lianwei.util

image.png

建表
新建数据库mybatis,新建表user

CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `sex` varchar(255) default NULL,
  `password` varchar(255) default NULL,
  `age` varchar(255) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8
image.png

建好表后,马上新增实体类User
User.java


/**
 * Created by Tired on 2019/8/6.
 */
public class User {
    private int id;
    private String name;
    private String password;
    private String sex;
    private String age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

entity包下新建UserMapper.xml实体映射文件(增删改查sql配置及实体映射配置)

UserMapper.xml





    
        
        
        
        
        
    

    
    
        INSERT into user (id,name,password,sex,age)
        values(#{id},#{name},#{password},#{sex},#{age})
    
    
    
        delete from user where id=#{id}
    
    
    
        update user set name=#{name}, password=#{password},sex=#{sex},age=#{age}
        where id=#{id}
    
    
    
    
    
    
    
    
    
    
    

util包下新建MybatisUtil(工具类,加载mybatis核心配置文件,获取数据库连接,得到sqlSession ,关闭sqlSession )
MybatisUtil.java

package com.lianwei.util;

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 java.io.IOException;
import java.io.Reader;
import java.sql.Connection;

/**
 * 工具类
 * @author AdminTC
 */
public class MybatisUtil {
    private static ThreadLocal threadLocal = new ThreadLocal();
    private static SqlSessionFactory sqlSessionFactory;
    /**
     * 加载位于src/mybatis.xml配置文件
     */
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    /**
     * 禁止外界通过new方法创建 
     */
    private MybatisUtil(){}
    /**
     * 获取SqlSession
     */
    public static SqlSession getSqlSession(){
        //从当前线程中获取SqlSession对象
        SqlSession sqlSession = threadLocal.get();
        //如果SqlSession对象为空
        if(sqlSession == null){
            //在SqlSessionFactory非空的情况下,获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession();
            //将SqlSession对象与当前线程绑定在一起
            threadLocal.set(sqlSession);
        }
        //返回SqlSession对象
        return sqlSession;
    }
    /**
     * 关闭SqlSession与当前线程分开
     */
    public static void closeSqlSession(){
        //从当前线程中获取SqlSession对象
        SqlSession sqlSession = threadLocal.get();
        //如果SqlSession对象非空
        if(sqlSession != null){
            //关闭SqlSession对象
            sqlSession.close();
            //分开当前线程与SqlSession对象的关系,目的是让GC尽早回收
            threadLocal.remove();
        }
    }

    /**
     * 测试
     */
    public static void main(String[] args) {
        Connection conn = MybatisUtil.getSqlSession().getConnection();
        System.out.println(conn!=null?"连接成功":"连接失败");
    }
}



dao包下新建UserTest测试类

package com.lianwei.dao;

import com.lianwei.entity.User;
import com.lianwei.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Tired on 2019/8/6.
 */
public class UserTest {
    public static void main(String[] args) {
        //增加
              User user = new User();
               user.setId(6);
               user.setName("张三");
               user.setPassword("123");
               user.setSex("男");
               user.setAge("23");
               addUser(user);
        //删除
        //deleteById(2);
        //修改
        //update(user);
        /*根据id查询一条*/
               /*User user =findById(1);
               System.out.println(user);*/
        //查询所有
               /*List list1 = findAll();
               for(User c:list1) System.out.println(c);*/
        //查询n条
               /*List list2 = findAllWithPage();
               for(User c:list2) System.out.println(c);*/
        //根据名字模糊查询n条
               /* List list3 = findByNameWithPage();
               for(User c:list3) System.out.println(c);*/
        //拼接sql语句
        //List list = findByDynaSql();
        //for(User c:list) System.out.println(c);

    }
    private static List findByDynaSql(){
        Map map = new HashMap();
        map.put("pname","上大号");
        map.put("psex","男");
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        List list = sqlSession.selectList(User.class.getName()+".findByDynaSql", map);
        sqlSession.commit();
        MybatisUtil.closeSqlSession();
        return list;
    }

    private static List findByNameWithPage() {
        Map map = new HashMap();
        map.put("name","%大%");
        map.put("pstart", 2);
        map.put("psize", 5);
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        List list = sqlSession.selectList(User.class.getName()+".findByNameWithPage", map);
        sqlSession.commit();
        MybatisUtil.closeSqlSession();
        return list;
    }

    private static List findAllWithPage() {
        Map map = new HashMap();
        map.put("pstart", 0);
        map.put("psize", 3);
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        List list = sqlSession.selectList(User.class.getName()+".findAllWithPage", map);
        sqlSession.commit();
        MybatisUtil.closeSqlSession();
        return list;
    }

    public static List findAll(){
        List list =null;
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            list = sqlSession.selectList(User.class.getName()+".findAll");
            sqlSession.commit();

        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            MybatisUtil.closeSqlSession();
        }
        return list;
    }

    public static User findById(int id){
        User user =null;
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            user = sqlSession.selectOne(User.class.getName()+".findById",id);
            sqlSession.commit();

        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            MybatisUtil.closeSqlSession();
        }
        return user;
    }

    public static void addUser(User user){
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            int i = sqlSession.insert(User.class.getName()+".addUser",user);
            sqlSession.commit();
            if(i>0) System.out.println("保存成功");
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            MybatisUtil.closeSqlSession();
        }


    }
    private static void deleteById(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            int i = sqlSession.delete(User.class.getName() + ".deleteById", id);
            sqlSession.commit();
            if (i > 0) System.out.println("根据id删除成功!");
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }

    private static void update(User user) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSqlSession();
            int i = sqlSession.update(User.class.getName() + ".update", user);
            sqlSession.commit();
            if (i > 0) System.out.println("修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            sqlSession.rollback();
        } finally {
            MybatisUtil.closeSqlSession();
        }
    }

}

最后,在核心配置文件中

  1. 设置实体类型别名,因为在实体映射文件中我们的paramType写的是user,这里的user其实是指com.lianwei.entity.User完整的路径

    
        
    
image.png
  1. 加载映射文件(框架启动时先加载mybatis核心配置文件,在此文件中加载实体映射文件)

    
        
    
image.png

测试--Run UserTest.java

image.png

你可能感兴趣的:(mybatis工作流程及基本CURD)