MyBatis框架入门小案例(关于用mybatis框架对数据库的增删改查)

(1)新建好maven基本项目,引入mabatis的依赖

MyBatis框架入门小案例(关于用mybatis框架对数据库的增删改查)_第1张图片

  说明:在以前的dao层我们通常是直接用一个dao方法来操作数据库的,这里我们要将dao的类改成一个接口类,在impl文件用另一个类来实现它的所有的抽象方法。

resources目录建一个mybatis-config.xml文件,这个是配置mybatis框架的主要配置,mapper下的UsersMapper.xml是用来配置mysql的映射语句

(2)、新建一个MyBatisUtil工具类:

package edu.nf.mybatis.tools;

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.InputStream;

/**
 * 描述:
 * mybatis工具类,这个工具类主要 是解析mybatis-config.xml,
 * 并初始化一个SqlSessionFactory工厂,然后通过这个工厂来创建SqlSession实例。
 * 一个SqlSessionr实例其实就是一个变相的Connection对象
 * @author lance
 * @create 2018-09-10 10:38
 */
public class MyBatisUtil {
   /**声明ggwhSqlSessionFactory*/
    private static SqlSessionFactory sqlSessionFactory;
   /* 在静态代码块中初始化SqlSessionFactory*/
    static{
        //找到mybatis-config.xml配置文件,并构建一个输入流
       //由于配置文件放在resources目录中,编译后会存放在classpath中
       try {
           //通过Resources类从classpath中找到xml文件并读取,返回一个InputStream的对象
           InputStream is =Resources.getResourceAsStream("mybatis-config.xml");
           //通过这个输入流来构建一个SqlSessionFactory对象
           //通过上面的输入流传递给builder对象进行解析
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
       } catch (IOException e) {
           throw new RuntimeException(e.getMessage());
       }
   }

   /**
    * 提供一个获取SqlSession的方法
    *
    * */
   public static SqlSession getSqlSession(){
       //openSession方法构建一个sqlSession对象
        return sqlSessionFactory.openSession();
   }
    public static SqlSession getSqlSession(Boolean falg){
        //openSession方法构建一个sqlSession对象
        return sqlSessionFactory.openSession(falg);
    }

}

 

(3)新建dao接口类与实现类具体如下:

UserDaoInf接口类:

package edu.nf.mybatis.dao;

import edu.nf.mybatis.entity.Users;

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

/**
 * @Author lance
 * */
public interface UserDaoInf {
    /**
     * 添加用户
     */
     void saveUser(Users users);

    /**
     * 修改用户
     */
     void updateUser(Users users);

    /**
     * 删除用户
     */
    void deleteUser(String uid);

    /**
     * 根据ID查询某条用户数据
     */
    Users findUsersById(String uid);

    /**
     * 查询所有的用户信息,保存在一个集合中
     */
    List findAll();
    /**
     * 统计查询
     */
    int userCount();
    /**
     * 模糊查询
     */
    List likeUsers(String name);
    /**
     * 查询所有的用户信息
     */
    List findAll2();
    /**
     * 查询单条的用户信息
     */
    Map findUserMap(String uid);
    /**
     * 查询多条的用户信息
     */
    List> findUserListMap();

  /**
   * 多条记录封装一个map,Map :键是这条记录的主键,值是封装实体的对象
  * @return
  */
  @MapKey("mid")
  Map getMateialMap();


   }

UserDaoImpl实现类:

package edu.nf.mybatis.dao.impl;

import edu.nf.mybatis.dao.UserDaoInf;
import edu.nf.mybatis.entity.Users;
import edu.nf.mybatis.tools.MyBatisUtil;
import javafx.beans.property.adapter.ReadOnlyJavaBeanBooleanProperty;
import org.apache.ibatis.session.SqlSession;

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

/**
 * 描述:
 * 接口实现类
 * @author lance
 * @create 2018-09-10 14:13
 */
public class UserDaoImpl implements UserDaoInf {

    @Override
    public int userCount() {
        SqlSession session = MyBatisUtil.getSqlSession();
        int count = 0;
        try {
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            count= dao.userCount();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            session.close();
        }
        return count;
    }

    @Override
    public List likeUsers(String name) {
        SqlSession session = MyBatisUtil.getSqlSession();
        List list = null;
        try {
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            list= dao.likeUsers(name);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            session.close();
        }
        return list;
    }

    @Override
    public void saveUser(Users user) {
        //获取SqlSession实例
        SqlSession session = MyBatisUtil.getSqlSession();
        try {
            //方式一:
            //获取相应的Mapper,getMapper方法需要传递一个接口的对象
            //并且返回的这个Mapper对象同样是实现了UserDao接口
            //这个Mapper对象最核心的作用就是和mybatis的mapper映射配置文件进行关联
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            //调用这个实现类的saveUser方法将数据保存在数据库中
            dao.saveUser(user);
            //方式二:
            //bint row = session.insert("edu.nf.mybatis.entity.saveUser",user);
            //手动提交事务
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            //在异常加回滚事务
            session.rollback();
        }finally {
            session.close();
        }
    }

    @Override
    public void updateUser(Users users) {
        SqlSession session = MyBatisUtil.getSqlSession();
        try{
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            dao.updateUser(users);
            session.commit();
        }catch (Exception e){
            e.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }
    }

    @Override
    public void deleteUser(String uid) {
        SqlSession session = MyBatisUtil.getSqlSession();
        try{
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            dao.deleteUser(uid);
            session.commit();
        }catch (Exception e){
            e.printStackTrace();
            session.rollback();
        }finally {
            session.close();
        }
    }

    @Override
    public Users findUsersById(String uid) {
        SqlSession session = MyBatisUtil.getSqlSession();
        Users user=null;
        try {
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            user = dao.findUsersById(uid);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            session.close();
        }
        return user;
    }

    @Override
    public List findAll() {
        List list = null;
        SqlSession session = MyBatisUtil.getSqlSession();
        try {
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            list = dao.findAll();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return list;
    }

    @Override
    public List findAll2() {
        SqlSession session = MyBatisUtil.getSqlSession();
        List list = null;
        try{
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            list = dao.findAll2();
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }finally {
            session.close();
        }
        return  list;
    }

    @Override
    public Map findUserMap(String uid) {
        SqlSession session = MyBatisUtil.getSqlSession();
        Map map = null;
        try {
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            map = dao.findUserMap(uid);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            session.close();
        }
        return map;
    }

    @Override
    public List> findUserListMap() {
        SqlSession session = MyBatisUtil.getSqlSession();
        List> list = null;
        try {
            UserDaoInf dao = session.getMapper(UserDaoInf.class);
            list = dao.findUserListMap();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }finally {
            session.close();
        }
        return list;
    }
}

(4)配置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>
    
    <typeAliases>
        
        
       
        <package name="edu.nf.mybatis.entity"/>
    typeAliases>

    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydb?useSSL=true&useUnicode=true&characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <mapper resource="mapper/UsersMapper.xml"/>
    mappers>
configuration>

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="edu.nf.mybatis.dao.UserDaoInf">
    
    
    <resultMap id="userMap" type="edu.nf.mybatis.entity.Users">
        <id property="uid" column="u_id">id>
        <result property="userName" column="u_name">result>
    resultMap>

  
    <insert id="saveUser" parameterType="users" >
        insert into user_info(u_id,u_name) values(#{uid},#{userName})
    insert>
    <update id="updateUser" parameterType="users">
        update user_info set u_name=#{userName} where u_id=#{uid}
    update>
    <delete id="deleteUser" parameterType="java.lang.String">
        delete from user_info where u_id=#{uid}
    delete>

    
    <select id="findUsersById" parameterType="java.lang.String" resultType="users">
        select u_id as uid, u_name as userName from user_info where u_id=#{uid}
    select>
    
    <select id="findAll" parameterType="users" resultType="users">
        select u_id as uid ,u_name as userName from user_info
    select>

    
    <select id="likeUsers" parameterType="java.lang.String" resultType="users">
        select u_id as uid,u_name as userName from user_info where u_name like #{userName}"%"
    select>

    
    <select id="userCount" resultType="int">
        select count(*) from user_info
    select>

    
    <select id="findAll2" parameterType="users" resultMap="userMap">
        select * from user_info
    select>

    
    <select id="findUserMap"  resultType="java.util.Map">
        select * from user_info where u_id = #{uid}
    select>

    
    <select id="findUserListMap" resultType="java.util.Map">
        select * from user_info
    select>
  
  
mapper>

(5)测试:

package eud.nf.mybatis.dao.test;

import edu.nf.mybatis.dao.UserDaoInf;
import edu.nf.mybatis.dao.impl.UserDaoImpl;
import edu.nf.mybatis.entity.Users;
import edu.nf.mybatis.tools.UUIDUtils;
import org.junit.Test;

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

/**
 * 描述:
 *
 * @author lance
 * @create 2018-09-10 15:15
 */
public class UserDaoImplTest {
    @Test
    public void testSaveUsers(){
        Users users = new Users();
        //users.setUid(UUIDUtils.createUUID());
        users.setUid("1007");
        users.setUserName("test6");
        UserDaoInf dao = new UserDaoImpl();
        dao.saveUser(users);
    }
    @Test
    public void testUpdateUsers(){
        Users users = new Users();
        users.setUid("1006");
        users.setUserName("admin");
        UserDaoInf dao = new UserDaoImpl();
        dao.updateUser(users);
    }
    @Test
    public void testDeleteUsers(){
        UserDaoInf dao = new UserDaoImpl();
        dao.deleteUser("1010");
    }
    @Test
    public void testFindUsersById(){
        UserDaoInf dao = new UserDaoImpl();
        Users user = dao.findUsersById("1001");
        System.out.println(user.getUid());
        System.out.println(user.getUserName());
    }
    @Test
    public  void testFindAll(){
        UserDaoInf dao = new UserDaoImpl();
        List list = dao.findAll();
        for (Users users : list) {
            System.out.println(users);
        }
    }
    @Test
    public void testUserCount(){
        UserDaoInf dao = new UserDaoImpl();
        int count = dao.userCount();
        System.out.println(count);
    }

    @Test
    public void testLikeUser(){
        UserDaoInf dao = new UserDaoImpl();
        List list = dao.likeUsers("test6");
        for (Users users : list) {
            System.out.println(users.getUid());
            System.out.println(users.getUserName());
        }
    }

    @Test
    public void testFindAll2(){
        UserDaoInf dao = new UserDaoImpl();
        List list = dao.findAll2();
        for (Users users : list) {
            System.out.println(users.getUid());
            System.out.println(users.getUserName());
        }
    }

    @Test
    public void testFindUsersMap(){
        UserDaoInf dao = new UserDaoImpl();
        Map map = dao.findUserMap("1001");
        for (String s : map.keySet()) {
            System.out.println(s +":"+ map.get(s));
        }
    }
    @Test
    public void testFindUsersListMap(){
        UserDaoInf dao = new UserDaoImpl();
        List> list = dao.findUserListMap();
        for (Map map : list) {
            for (String s : map.keySet()) {
                System.out.println(s+":"+map.get(s));
            }
            System.out.println("---------");
        }
    }

}

 

转载于:https://www.cnblogs.com/gepuginy/p/9631074.html

你可能感兴趣的:(MyBatis框架入门小案例(关于用mybatis框架对数据库的增删改查))