mybatis-增删改查和配置

加入log4j日志功能

  1. 加入依赖
    <!-- log4j日志 -->
    <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
    </dependency>
    
  2. 加入log4j的配置文件
    • log4j的配置文件名为log4j.xml,存放的位置是src/main/resources目录下
    • 日志的级别:FATAL(致命)>ERROR(错误)>WARN(警告)>INFO(信息)>DEBUG(调试) 从左到右打印的内容越来越详细
    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
        <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
            <param name="Encoding" value="UTF-8" />
            <layout class="org.apache.log4j.PatternLayout">
    			<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
            </layout>
        </appender>
        <logger name="java.sql">
            <level value="debug" />
        </logger>
        <logger name="org.apache.ibatis">
            <level value="info" />
        </logger>
        <root>
            <level value="debug" />
            <appender-ref ref="STDOUT" />
        </root>
    </log4j:configuration>
    

MyBatis的增删改查

  1. 添加
    <!--int insertUser();-->
    <insert id="insertUser">
    	insert into t_user values(null,'admin','123456',23,'男','12345@qq.com')
    </insert>
    
  2. 删除
    <!--int deleteUser();-->
    <delete id="deleteUser">
        delete from t_user where id = 6
    </delete>
    
  3. 修改
    <!--int updateUser();-->
    <update id="updateUser">
        update t_user set username = '张三' where id = 5
    </update>
    
  4. 查询一个实体类对象
    <!--User getUserById();-->  
    <select id="getUserById" resultType="com.atguigu.mybatis.bean.User">  
    	select * from t_user where id = 2  
    </select>
    
  5. 查询集合
    <!--List<User> getUserList();-->
    <select id="getUserList" resultType="com.atguigu.mybatis.bean.User">
    	select * from t_user
    </select>
    
  • 注意:

    1. 查询的标签select必须设置属性resultType或resultMap,用于设置实体类和数据库表的映射关系
      • resultType:自动映射,用于属性名和表中字段名一致的情况
      • resultMap:自定义映射,用于一对多或多对一或字段名和属性名不一致的情况
    2. 当查询的数据为多条时,不能使用实体类作为返回值,只能使用集合,否则会抛出异常TooManyResultsException;但是若查询的数据只有一条,可以使用实体类或集合作为返回值

测试类

juit测试类


import com.atguigu.mybatis.mapper.userMapper;
import com.atguigu.mybatis.pojo.user;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisTest {
    /**
     * 往t_user表中插入数据
     * @return 1
     * @throws IOException
     */
    @Test
public void testInsertUser() throws IOException {
    //读取MyBatis的核心配置文件
    InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
    //获取SqlSessionFactoryBuilder对象
    SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
    //通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory,生产SqlSession对象
    SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
    //获取sqlSession,此时通过SqlSession对象所操作的sql都必须手动提交或回滚事务
    //SqlSession sqlSession = sqlSessionFactory.openSession();
    //创建SqlSession对象,此时通过SqlSession对象所操作的sql都会自动提交
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //通过代理模式创建UserMapper接口的代理实现类对象
    userMapper userMapper = sqlSession.getMapper(userMapper.class);
    //调用UserMapper接口中的方法,就可以根据UserMapper的全类名匹配元素文件,通过调用的方法名匹配映射文件中的SQL标签,并执行标签中的SQL语句
    int result = userMapper.insertUser();
    //提交事务
    //sqlSession.commit();
    System.out.println("result:" + result);
}

    /**
     * 往t_user表中更新数据
     * @throws IOException
     */
    @Test
    public void testUpdateUser() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactoryBuilder.build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        userMapper mapper = sqlSession.getMapper(userMapper.class);
        mapper.updateUser();
        System.out.println("1111");
    }

    /**
     * 删除t_user表中的数据
     * @throws IOException
     */
    @Test
    public void testDeleteUser() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactoryBuilder.build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        userMapper mapper = sqlSession.getMapper(userMapper.class);
        mapper.deleteUser();
    }

    /**
     * 通过id来查询t_user表格
     * @throws IOException
     */
    @Test
    public void  testGetUserById() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactoryBuilder.build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        userMapper mapper = sqlSession.getMapper(userMapper.class);
        user userById = mapper.getUserById();
        System.out.println(userById.toString());

    }

    /**
     * 查询t_user表中所有的数据
     * @throws IOException
     */
    @Test
    public void TestGetAllUser() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactoryBuilder.build(resourceAsStream);
        SqlSession sqlSession = build.openSession(true);
        userMapper mapper = sqlSession.getMapper(userMapper.class);
        List<user> allUser = mapper.getAllUser();
        allUser.forEach(user -> System.out.println(user.toString()));
    }
}

结果

posted @ 2022-07-03 17:55  wiselee/  阅读(19)  评论(0编辑  收藏  举报