The first chapter of MyBatis builds the operating environment of MyBatis


insert image description here

structure diagram

1. Create a Maven project

1 The packaging method is set to jar

2 Introduce dependencies

2. Create the core configuration file of MyBatis

The framework is the jar package plus the configuration file.
The core configuration file is customarily named
mybatis-config.xml.
After integrating the Spring framework, this configuration file can be omitted.

1 Configure the core file

<?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/eshop"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--引入映射文件
    复数标签套单数标签的格式

    -->
    <mappers>
        <mapper resource="mappers/UserMapper.xml"/>
    </mappers>
</configuration>

Note: A character set error may be reported in the core file

Unknown initial character set index '255' received from server. Initial client character

If it is solved, add a character setting in the back

dbc:mysql://localhost:3306/eshop?useUnicode=true&amp;characterEncoding=utf8

2 Create a mapper interface

The mapper interface in MyBatis is equivalent to the previous dao. But the difference is that mapper is just an interface, and we don't need to provide an implementation class.

package com.xyt.mabatis.mapper;

public interface UserMapper {
    
    
    int insertUser();
}

3 Create a mapping file for mabatis

Object Relational Mapping

ORM: Object Relational Mapping
Object: java entity class object
Relationship: relational database
Mapping: the corresponding relationship between the two
insert image description here
The instantiated object of the class describes a specific transaction. a row in the table

<?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.xyt.mybatis.mapper.UserMapper">
    <!--int insertUser();-->
    <insert id="insertUser">
        insert into t_user values (1,'张三','123',22,'男','[email protected]')
    </insert>

</mapper>

Note: This field name must correspond to the field name in the database

4 How to write the test file

insert image description here

insert image description here

package com.xyt.mybatis.test;

import com.xyt.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;
import java.util.List;


public class MabitsTest1 {
    
    

    /**
     * SqlSession默认不自动提交事务,若需要自动提交事务
     * 可以使用SqlSessionFactory.openSession(true);
     */


    @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(true);
        //获取mapper接口对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //测试功能
        int result = mapper.insertUser();
        //提交事务
        sqlSession.commit();
        System.out.println("result:"+result);
    }


}

Executed twice, there are two more data in the database
insert image description here

5 If you need code, you can visit the gitee warehouse to have a look

https://gitee.com/wang-sanfeng123/MyBatisTest

6 log4j log function

Configure this log4j file in the child pom

<!-- log4j日志 -->
<dependency> 
  <groupId>log4j</groupId>
  <artifactId>log4j</artifactId>
  <version>1.2.7</version> 
 </dependency>

The log4j configuration file is named log4j.xml, and is stored in the src/main/resources directory

<?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>

Log level
FATAL (fatal)>ERROR (error)>WARN (warning)>INFO (information)>DEBUG (debugging)
The content printed from left to right becomes more and more detailed . If an error is reported
when configuring log related files
, fill in Related information goes in

insert image description here
After the log runs, the generated information is shown in the figure below

DEBUG 05-14 21:53:09,963 ==>  Preparing: insert into t_user values (6,'张三','123',22,'男','[email protected]') (BaseJdbcLogger.java:137) 
DEBUG 05-14 21:53:09,986 ==> Parameters:  (BaseJdbcLogger.java:137) 
DEBUG 05-14 21:53:09,998 <==    Updates: 1 (BaseJdbcLogger.java:137) 
result:1

It reflects the executed sql statement and the number of affected rows

Three first change the method, then change the mapping file

1 The role of Test annotations

@Test
注解是JUnit测试的基础,JUnit 4的优势就在于支持了注解。
@Test
的使用 是该方法可以不用main方法调用就可以测试出运行结果,是一种测试方法,

一般函数都需要有main方法调用才能执行,注意被测试的方法必须是public修饰的。

2 Add test code for modifying user information

public  void  testUpdate() throws IOException{
    
    
        InputStream inputStream=Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory
                =new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession =sqlSessionFactory.openSession(true);
        UserMapper mapper=sqlSession.getMapper(UserMapper.class);
        mapper.deleteUser();
    }
DEBUG 05-14 23:07:28,488 ==>  Preparing: DELETE from t_user where username='lisi'; (BaseJdbcLogger.java:137) 
DEBUG 05-14 23:07:28,524 ==> Parameters:  (BaseJdbcLogger.java:137) 
DEBUG 05-14 23:07:28,546 <==    Updates: 1 (BaseJdbcLogger.java:137) 

3 Code to find user information

insert image description here
resultType: the same number of database fields and attributes

java.lang.NoSuchMethodError: 'boolean org.apache.log4j.Logger.isTraceEnabled()

Law

 <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>

result

DEBUG 05-15 01:24:01,095 ==>  Preparing: select * from t_user where id=6; (BaseJdbcLogger.java:137) 
DEBUG 05-15 01:24:01,136 ==> Parameters:  (BaseJdbcLogger.java:137) 
DEBUG 05-15 01:24:01,173 <==      Total: 1 (BaseJdbcLogger.java:137) 
User{
    
    id=6, username='张三', password='123', age=22, sex='男', email='[email protected]'}

4 RESULT

DEBUG 05-15 01:33:26,591 ==>  Preparing: select * from t_user where id=6; (BaseJdbcLogger.java:137) 
DEBUG 05-15 01:33:26,626 ==> Parameters:  (BaseJdbcLogger.java:137) 
DEBUG 05-15 01:33:26,650 <==      Total: 1 (BaseJdbcLogger.java:137) 
User{
    
    id=6, username='张三', password='123', age=22, sex='男', email='[email protected]'}
DEBUG 05-15 01:33:26,652 ==>  Preparing: select * from t_user; (BaseJdbcLogger.java:137) 
DEBUG 05-15 01:33:26,653 ==> Parameters:  (BaseJdbcLogger.java:137) 
DEBUG 05-15 01:33:26,659 <==      Total: 8 (BaseJdbcLogger.java:137) 
User{
    
    id=1, username='张三', password='123', age=22, sex='男', email='[email protected]'}
User{
    
    id=2, username='张三', password='123', age=22, sex='男', email='[email protected]'}
User{
    
    id=4, username='张三', password='123', age=22, sex='男', email='[email protected]'}
User{
    
    id=6, username='张三', password='123', age=22, sex='男', email='[email protected]'}
User{
    
    id=7, username='张三', password='123', age=22, sex='男', email='[email protected]'}
User{
    
    id=8, username='张三', password='123', age=22, sex='男', email='[email protected]'}
User{
    
    id=9, username='张三', password='123', age=22, sex='男', email='[email protected]'}
User{
    
    id=10, username='张三', password='123', age=22, sex='男', email='[email protected]'}

Four specific steps to add properties

1 Basic Features

  • jdbc.properties is a Java properties file used to configure the properties of the Java Database Connectivity (JDBC) driver, such as database connection URL, user name, password, driver class name, etc.
  • These properties are read in the Java application in order to connect to the database and perform database operations. JDBC properties files are usually used in Java web applications or desktop applications to more conveniently configure database connection information without hardcoding such information in the code.

2 The traditional method of obtaining database links

jdbc.properties配置mysql8.的步骤如下:

在项目中创建jdbc.properties文件。

在jdbc.properties文件中添加以下配置:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
jdbc.username=用户名
jdbc.password=密码

其中,jdbc.driver为MySQL驱动程序的类名,jdbc.url为连接MySQL数据库的URL,jdbc.username为连接MySQL数据库的用户名,jdbc.password为连接MySQL数据库的密码。

将MySQL的驱动程序(mysql-connector-java.jar)放置在项目的classpath中。

在Java代码中使用以下代码获取数据库连接:

Properties props = new Properties();
InputStream in = getClass().getResourceAsStream("/jdbc.properties");
props.load(in);
in.close();

String driver = props.getProperty("jdbc.driver");
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");

Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);

其中,getClass().getResourceAsStream("/jdbc.properties")用于获取jdbc.properties文件的输入流,props.load(in)用于加载jdbc.properties文件中的配置。最后,使用DriverManager.getConnection()方法获取数据库连接。


3 The way to get the database interface in mybatis

The jdbc.properties file in MyBatis is a configuration file used to configure the data source and JDBC connection properties of MyBatis. This file typically contains the following attributes:

driver: The name or class name of the JDBC driver.
url: JDBC database connection URL.
username: database username.
password: database password.
initialSize: The initial size of the connection pool.
maxActive: The maximum number of active connections for the connection pool.
maxIdle: The maximum number of idle connections in the connection pool.
minIdle: The minimum number of idle connections in the connection pool.
When using MyBatis for database access, you can configure MyBatis' data source and JDBC connection properties by reading these properties in the jdbc.properties file.

Five setting category aliases

1 core configuration file

Add some information
type in mybatis-config.xml: If the target alias that needs to be simplified and described
is not set, the default is the class name. If it is set, it is a value defined by itself

 <!--设置类型别名的方法-->
    <typeAliases>
        <typeAlias type="com.xyt.mybatis.pojo.User" alias="User"></typeAlias>
    </typeAliases>

The meaning is to write less things in UserMapper.xml

 <select id="getUserList" resultType="User">
       select * from t_user;
    </select>

2 Introduce a configuration file in the core file

 <!--引入映射文件-->
    <mappers>
        <!--<mapper resource="mappers/UserMapper.xml"/>-->
        <!--
            以包为单位引入映射文件
            要求:
            1、mapper接口所在的包要和映射文件所在的包一致
            2、mapper接口要和映射文件的名字一致
        -->
        <package name="com.xyt.mybatis.mapper"/>
    </mappers>

Modify the core file location under the path
insert image description here
com.xyt, mybatis, and mapper files under the resource location

Guess you like

Origin blog.csdn.net/CNMBZY/article/details/130652451