MyBatis简单快速使用入门-个人使用

第一步导包

eclipse用lib导入mybatis-3.5.2.jar(直接百度下载)idea直接在pom.xml直接导入

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
</dependency>

config文件 头文件都是一样的 直接复制可用

<?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">
<!-- mybatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置mysql的环境-->
        <environment id="mysql">
            <!-- 配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置数据源(连接池) -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/news"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
    <mappers>
       
        <mapper resource="NewsDao.xml"/>
      
    </mappers>
</configuration>

对应的配置文件

<?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="org.news.dao.UserDao">
    <select id="findUser" resultType="org.news.entity.User">
        select * from news_users where uname=#{arg0} and upwd=#{arg1}
    </select>
    <delete id="delUser">
        
    </delete>
</mapper>

简单的SQLSession工厂工具类

package org.news.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;

/**
 * @author Administrator
 * @date 2020-02-21 10:34
 */
public class MyBatisUtil {
    private static SqlSessionFactory sessionFactory = null;
    /**
     * 创建本地线程变量,为每一个线程独立管理一个session对象 每一个线程只有且仅有单独且唯一的一个session对象
     * 加上线程变量对session进行管理,可以保证线程安全,避免多实例同时调用同一个session对象
     * 每一个线程都会new一个线程变量,从而分配到自己的session对象
     */
    private static ThreadLocal<SqlSession> threadlocal = new ThreadLocal<SqlSession>();

    // 创建sessionFactory对象,因为整个应用程序只需要一个实例对象,故用静态代码块
    static {
        try {
            Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回sessionFactory对象 工厂对象
     *
     * @return sessionFactory
     */
    public static SqlSessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * 新建session会话,并把session放在线程变量中
     */
    private static void newSession() {
        // 打开一个session会话
        SqlSession session = sessionFactory.openSession();
        // 将session会话保存在本线程变量中
        threadlocal.set(session);
    }

    /**
     * 返回session对象
     * @return session
     */
    public static SqlSession getSession(){
        //优先从线程变量中取session对象
        SqlSession session = threadlocal.get();
        //如果线程变量中的session为null,
        if(session==null){
            //新建session会话,并把session放在线程变量中
            newSession();
            //再次从线程变量中取session对象
            session = threadlocal.get();
        }
        return session;
    }

    /**
     * 关闭session对象,并从线程变量中删除
     */
    public static void closeSession(){
        //读取出线程变量中session对象
        SqlSession session = threadlocal.get();
        //如果session对象不为空,关闭sessoin对象,并清空线程变量
        if(session!=null){
            session.close();
            threadlocal.set(null);
        }
    }
}

业务层使用

package org.news.test;


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 org.junit.Test;
import org.news.dao.CommentsDao;
import org.news.dao.NewsDao;
import org.news.dao.UserDao;
import org.news.entity.News;
import org.news.entity.User;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * mybatis的入门案例
 */
public class MybatisTest {

    /**
     * 入门案例
     * @param args
     */
    public static void main(String[] args)throws Exception {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        UserDao userDao = session.getMapper(UserDao.class);
        //5.使用代理对象执行方法
        User user = userDao.findUser("admin","admin");
        System.out.println(user.getUname());
       /* for(User user : users){
            System.out.println(user);
        }*/
        //6.释放资源
        session.close();
        in.close();
    }
    @Test
    public void deleteCommentsByNids()throws Exception{
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        NewsDao newsDao=session.getMapper(NewsDao.class);
        CommentsDao commentsDao=session.getMapper(CommentsDao.class);
        int[] list={81,82};
        commentsDao.deleteCommentsByNids(list);
        newsDao.deleteNewsByList(list);
        //6.释放资源
        session.close();
        in.close();
    }
    @Test
    public void getAllnewsByTID() throws IOException, SQLException {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        NewsDao newsDao=session.getMapper(NewsDao.class);
        List<News> list=newsDao.getPageNewsList(null,1,5);
        for (News news:list){
            System.out.println(news.getNtitle());
        }
        //6.释放资源
        session.close();
        in.close();
    }
}

**

这只是一个萌新自用复习的,大佬们勿喷!!!

球球了!!!!!

**

发布了2 篇原创文章 · 获赞 1 · 访问量 67

猜你喜欢

转载自blog.csdn.net/qq_44880019/article/details/104553376