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


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

      说明:在以前的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<Users> findAll();
        /**
         * 统计查询
         */
        int userCount();
        /**
         * 模糊查询
         */
        List<Users> likeUsers(String name);
        /**
         * 查询所有的用户信息
         */
        List<Users> findAll2();
        /**
         * 查询单条的用户信息
         */
        Map<String ,Object> findUserMap(String uid);
        /**
         * 查询多条的用户信息
         */
        List<Map<String,Object>> findUserListMap();

      /**
       * 多条记录封装一个map,Map<Integer,Material> :键是这条记录的主键,值是封装实体的对象
      * @return
      */
      @MapKey("mid")
      Map<Integer,Material> 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<Users> likeUsers(String name) {
            SqlSession session = MyBatisUtil.getSqlSession();
            List<Users> 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<Users> findAll() {
            List<Users> 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<Users> findAll2() {
            SqlSession session = MyBatisUtil.getSqlSession();
            List<Users> 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<String, Object> findUserMap(String uid) {
            SqlSession session = MyBatisUtil.getSqlSession();
            Map<String,Object> 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<Map<String, Object>> findUserListMap() {
            SqlSession session = MyBatisUtil.getSqlSession();
            List<Map<String, Object>> 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用于给类型指定别名-->
        <typeAliases>
            <!--方式一:type属性是使用完整的类名,alias属性是别名-->
            <!--<typeAlias type="edu.nf.mybatis.entity.Users" alias="Users"/>-->
           <!-- 方式二:直接给整个实体包定义别名,name属性指定实体类所在的包名,这样会为每一个实体类自动
            生成一个别名,而这个 别名就是实体类的类名并且首字母小写-->
            <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&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                    <property name="username" value="root"/>
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
        </environments>
        <!--将所有的mapper映射配置文件加入到mapper配置中-->
        <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指定Dao接口的完整类名
        mybatis会依据这个接口动态创建一个实现类去实现这个接口
        而这个实现类是一个Mapper对象-->
    <mapper namespace="edu.nf.mybatis.dao.UserDaoInf">
        <!--在mapper里面就可以配置基于mybatis的增删查改的sql映射配置-->
        <!--插入操作,id指定UserDao接口中的方法名,
        parameterType为指定方法参数的类型,。也可以定义为TypeAlias中定义的别名
        useGeneratedKeys属性设置为true表示使用主键自增长
        keyProperty属性指定实体中需要自增长的字段名称
    
        sql设置参数的时候使用#{},#{}是一个ognl表达式,(对象图导航语言)
        而这里的#{}中指定的实体中的字段名
        -->
        <resultMap id="userMap" type="edu.nf.mybatis.entity.Users">
            <id property="uid" column="u_id"></id>
            <result property="userName" column="u_name"></result>
        </resultMap>
    
      <!--id中要指定接口的方法-->
        <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>
    
        <!--根据ID来查询某条用户的信息,有参数类型的话要指定参数的类型,在parameterType属性中指定-->
        <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>
    
        <!--统计查询,返回int类型的数据(指定返回值的类型)-->
        <select id="userCount" resultType="int">
            select count(*) from user_info
        </select>
    
        <!--将数据存放在一个resultMap集合中,用resultMap集合来映射-->
        <select id="findAll2" parameterType="users" resultMap="userMap">
            select * from user_info
        </select>
    
        <!--使用map集合映射,映射单条信息-->
        <select id="findUserMap"  resultType="java.util.Map">
            select * from user_info where u_id = #{uid}
        </select>
    
        <!--使用map映射多条信息-->
        <select id="findUserListMap" resultType="java.util.Map">
            select * from user_info
        </select>
      
    <!--使用Map来映射一个实体的对象,实体的ID作为主键-->
      <select id="getMateialMap" resultMap="helpMap">
       select * from Material
      </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<Users> 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<Users> 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<Users> 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<String,Object> 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<Map<String,Object>> list = dao.findUserListMap();
            for (Map<String, Object> map : list) {
                for (String s : map.keySet()) {
                    System.out.println(s+":"+map.get(s));
                }
                System.out.println("---------");
            }
        }
    
    }
  • 相关阅读:
    Thinkphp3.2 PHPMailer 发送邮件
    13 代理模式
    12 状态模式
    11 组合模式
    10 迭代器模式
    9 模板方法模式
    8 外观模式
    MySQL Network--Localhost与127.0.0.1的差异
    MySQL Memory--内存分配相关参数
    mysqldump命令之single-transaction
  • 原文地址:https://www.cnblogs.com/gepuginy/p/9631074.html
Copyright © 2020-2023  润新知