Tin的java笔记 www.tinstu.com

MyBatis:框架的搭建及测试

1.开发环境

新建一个工程-配置jdk版本-配置maven

2.创建maven工程

修改打包方式为jar

导入依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.tinstu.mybatis</groupId>
    <artifactId>MyBatis_demo1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <!-- Mybatis核心 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!-- junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- MySQL驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.3</version>
        </dependency>
    </dependencies>


</project>

 

3.创建MyBatis的核心配置文件  mybatis-config.xml

在resources下创建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>
    <!--设置连接数据库的环境-->
    <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"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件-->
    <mappers>
        <mapper resource="mappers/UserMapper.xml"/>
    </mappers>
</configuration>

 4.创建mapper接口 UserMapper.java

MyBatis中的mapper接口相当于以前的dao,但是区别于,mapper仅仅是接口,我们不需要提供实现类

先在 mybatis-config.xml中配置好数据库信息,创建一个数据库,创建实体类User.java

创建一个接口  UserMapper.java

package com.tinstu.mybatis.mapper;
public interface UserMapper {

  //添加用户信息
  int insertUser();
}

 5.创建MyBatis的映射文件    UserMapper.xml

MyBatis面向接口编程的两个一致
  • 1.映射文件UserMapper.xml的 namespace和mapper接口UserMapper.java的全类名保持一致 <mapper namespace="com.tinstu.mybatis.mapper.UserMapper">
  • 2.映射文件中sql语句的id要和mapper接口中的方法名一致 (此映射文件中事务id=insertUser和上面接口中的方法名insertUser一样)
表---实体类---mapper接口---映射文件

mapper接口的全类名和映射文件的命名空间(namespace)保持一致

    • mapper接口中方法的方法名和映射文件中编写SQL的标签的id属性保持一致

<?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="com.tinstu.mybatis.mapper.UserMapper">
    <!--int insertUser();-->
    <insert id="insertUser">
        insert into t_user values(null,'张三','123','123123@qq.com')
    </insert>
</mapper>
最后还要在配置文件mybatis-config.xml中引入映射文件
<!--引入映射文件--> 
<mappers> 
      <mapper resource="mappers/UserMapper.xml"/> 
</mappers>

6.测试添加功能

创建一个测试类
package com.tinstu.mybatis;

import com.tinstu.mybatis.mapper.UserMapper;
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;

public class Mybatistest {
@Test
public void testmybatis() throws IOException{
//加载核心配置文件
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
//获取SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//获取sqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取mapper接口对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class) ;
//测试功能
int result = mapper.insertUser();
//提交事务
sqlSession.commit();

}

}


 

 

7.优化功能

1.SqlSession默认不自动提交事务,如需要自动提交事务,可以使用SqlSessionFactory.openSession(true);
        //获取SqlSession(加入true)
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //获取mapper接口对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class) ;
        //测试功能
        int result = mapper.insertUser();
        //提交事务(删掉)
       // sqlSession.commit();
2.加入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>
 

8.测试删除修改功能

(1)修改

UserMapper.xml中加入

    <!--void updateUser();-->
    <update id="updateUser">
        update user set username = '张三55' where id = 3 ;
    </update>

测试类

   @Test
    public void testuodate() throws IOException{
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updateUser();
   }

删除:

    <!--void deleteUser();-->
    <delete id="deleteUser">
        delete from user where id = 5
    </delete>

 

9.测试查询功能

(1)根据id查询

UserMapper.java中添加查询方法

    //查询功能
    User getUser();

UserMapper.xml中写sql语句

    <!--void getUser();-->
    <!--
        查询功能的标签必须设置resultType或resultMap
        resultType:设置默认的映射关系
        resultMap:设置自定义的映射关系
    -->
    <select id="getUser" resultType="com.tinstu.mybatis.pojo.User">
        select * from user where  id=3
    </select>

测试类:

   @Test
    public void testuodate() throws IOException{
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUser();
       System.out.println(user);
   }

(2)查询所有

UserMapper.java中添加查询方法

    //查询所有
    List<User> getUserAll();

UserMapper.xml中写sql语句

    <!--List<User> getUserAll();-->
    <select id="getUserAll" resultType="com.tinstu.mybatis.pojo.User">
        select * from user
    </select>

测试类:

   @Test
    public void testuodate() throws IOException{
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
       List<User> userList = mapper.getUserAll();
       System.out.println(userList);
       //lanmbda表达式
       userList.forEach(user -> System.out.println(user));
   }

我的java笔记:mybatis环境搭建及测试: https://www.tinstu.com/1218.html

posted @ 2022-04-25 17:06  Tinstu  阅读(289)  评论(0编辑  收藏  举报