在Idea中Maven环境下Mybatis的简洁配置

关于mybatis配置环境问题

1.resources文件下配置(mybatis_congig.xml):


<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://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            dataSource>
        environment>
    environments>

    <mappers>
        <mapper resource="com/muzi/Dao/UserMapper.xml"/>
    mappers>
configuration>
2.在src下创建三级包mybatisUtils:
package com.muzi.Untils;

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;

//建设工厂
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //第一步//获取sqlSessionFactory
            String resource= "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
        //获取 SqlSession
        public static SqlSession getSqlSession (){
            /*SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;*/
            /*简化为*/
            return sqlSessionFactory.openSession();

        }

}
3.在dao层创建usermapper映射接口和uermapper.xml:
  • UserMaspper.xml


        

    
    
  • UserMapper.java
    package com.muzi.Dao;
    
    import com.muzi.entity.User;
    
    import java.util.List;
    
    public interface UserMapper {
        //查询全部用户
        List<User> getUserList();
    
4.最后编写测试类(test测试需对应实体包):

Test测试类:

package com.muzi.Dao;
import com.muzi.Untils.MybatisUtils;
import com.muzi.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/*
增删改需要提交事务(注意)
 */
public class UserTest{
    @Test
    public void test(){
        //获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //执行sql
        UserMapper userDao = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userDao.getUserList();
        for (User user : userList) {
            System.out.println(user);
        }
        //关闭资源
        sqlSession.close();
        }

你可能感兴趣的:(在Idea中Maven环境下Mybatis的简洁配置)