Mybatis study notes 1 Getting started with Mybatis

Almost according to the mybatis Chinese documentation: Create the first mybatismaven project and run it

Getting Started_MyBatis Chinese Website

Create new library

Create table

Create project

After restarting

Configuring Maven and encoding has become a habit

New module

Note: The GroupId and ArtifactId version are the package path and package name that will be stored when you use Maven to install them.

Directory structure: Although I changed to JDK17, the compiler version does not seem to work. The IDEA version may be low.

Suddenly found that maven was missing

enter

Maven projects

Select the corresponding pom.xml

maven is back

I'd better change JDK to 8.

Official website meaning, build SqlSessionFactory from XML

In other words, this XML is actually configuring SqlSessionFactory

  Also talked about the method of not using XML configuration

First configure according to XML

It doesn’t matter what the name of the new mybatis-config.xml file is under Resources.

Let’s talk about it here: Some configuration files are like a template, which are often used. You can configure the templates of some commonly used files through idea.

So that you can create it directly next time you use it. The specific method is

IDEA common template file configuration_biubiubiu0706's blog-CSDN blog

Here I will copy it according to Mybatis Getting Started

Complete the JDBC connection driver, URL, username, and password first.



Next

After executing the Mybatis program written below, I found that the database was not inserted.

The reason is that the sqlSession object obtained by Mybatis by default does not support default submission.

Take a look at which implementation class is SqlSessionFactory and sqlSession -------->DefaultSqlSessionFactory and DefaultSqlSession If you are interested in the source code, you can take a look

Generally, a database corresponds to a SqlSessionFactory object.

A few details:

The mybatis core configuration file can be named as you want, and the location can also be placed as you want (for program robustness and portability, it is best to place it in the resources directory)

The sql statement in xxxMaper.xml of mybatis can be ; (end with semicolon) or can be omitted.

Multiple different sqlSession objects can be obtained through the same SqlSessionFactory object.

Resources.getResourceAsStream("mybatis-config.xml"); This is the API encapsulated by mybatis. Generally, when you encounter Resources, it is in the resources directory. Add your mybatis configuration file to yyy.xml under the xxx package under resources.

So

InputStream inputStream = Resources.getResourceAsStream("xxx/yyy.xml");

Get an input stream

Then stream the input into the build method

SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);

So can you create a new stream yourself? It is also possible, for example, put the configuration file in a directory on the D drive

InputStream in=new FileInputStream("d:\\mybatis-config.xml")

或者InputStream in=new FileInputStream("d:/mybatis-config.xml")

But the disadvantage of this is that it has poor portability, and it won’t work on Apple computers.

It can be used anywhere in the specified resources directory.

In addition, there is another way to load the mybatis core configuration file using a class loader to obtain the system class loader's method of calling getResourceAsStream("file name")

InputStream in=ClassLoader.getSystemClassLoad().getResourceAsStream("mybatis-config.xml");

In fact, you can also directly use InputStream in=ClassLoader.getSystemResourceAsStream("mybatis-config.xml");

<!--The resource attribute will automatically search for resources from the root path of the class-->
<!--
1. The <package name="package name"> tag is used to automatically scan the mapping file under the specified package. The mapping file name and the interface name are required to be consistent, and the mapping file (.xml) and the interface need to be in the same package, otherwise it will Report an error.
2. The class attribute of the <mapper class=""> tag is used to register the mapping file. The mapping file name and the interface name are also required to be consistent, and the mapping file (.xml) and the interface need to be in the same package, otherwise an error will be reported.
3. The <mapper resource="org/xx/demo/mapper/xx.xml"/> tag is used to register the mapping file. Unlike the above two methods, this method does not require the mapping file name and the interface name to be consistent. Here, the namespace corresponds to the mapper interface. The namespace must be consistent with the fully qualified name of the interface.
4. <mapper url="file:///d:/CarMapper.xml" /> loads the mapping file from an absolute path, and the name of the .xml file does not need to be the same as the interface name. Specify and interface relationships through namespaces
-->
<!--Tell mybatis where to find the mapper file-->
<mappers>
    <mapper resource="mapper/CarMapperABC.xml"/>
</mappers>

About the transaction management mechanism of Mybatis

 <!--
     transactionManager: transaction manager
     There are two types of values:
     1:type="JDBC", use java.sql.Connection to manage transactions
     2:type="MANAGED", the documentation explains, does almost nothing. It does not commit or rollback a connection, but lets the container manage the entire life cycle of the transaction.
 -->
 <!--
    mybatis provides two transaction management mechanisms
    1. JDBC (can be lowercase) transaction manager: the mybatis framework manages transactions by itself. In fact, it uses native JDBC code to manage transactions.
        For example, when writing JDBC: conn.setAutoCommit(false);
                    ...business processing...
                    conn.commit();Manual submission
    2.MANAGED (can be lowercase) transaction manager
        Mybatis no longer manages transactions, and the transactions are handed over to other containers: such as Spring
        But MANAGED is used here, because if there is no container, for example, if the transaction is not opened, it will become like there is no transaction, so just do it.
-->
 <transactionManager type="JDBC"/>

If the transaction manager type used is JDBC

SqlSession sqlSession = sqlSessionFactory.openSession();

The bottom layer of this code will execute conn.setAutoCommit(false);

If the transaction manager type used is MANAGED, it will be managed by the container. For example, it will be managed by Spring. Generally, there will be no transaction and it will be automatically submitted.

openSession has an overloaded method:

SqlSession sqlSession = sqlSessionFactory.openSession(true); means automatic submission

In a JDBC transaction, if conn.setAutoCommit(false); is not set, conn.getAutoConmmit() itself is true;

 After the above introduction, write an almost complete version of the Mybatis entry program

For the convenience of future testing, if you don’t need to test one, just write a main method and introduce JUnit (unit test)

Create a new module to test Junit

Maven project

Introduce dependencies

For example, if you need to test the business method

Build a test class under the test package. This assertion is very useful.

Introduction of junit into Mybatis

Write Mybatis program in unit test

You can see that there is no log output now

About Mybatis integrated log framework logback. It can make debugging more convenient

The following records are previous study records

In addition, when you click in the configuration file, there is a problem with the order of the labels. You need to order them in order.

About integrating the log framework logback in Mybatis in the configuration file.

In the official document settings

This will have log output

However, if you want to use richer logs such as detailed time and thread name, you can integrate third-party dependencies.

SLF4 (Salad style): SLF4 is a logging standard. There is a framework called logback, which implements the SLF4 specification.

LOG4J:

LOG4J2:

STDOUT_LOGGING: Mybatis built-in standard log implementation

....

Note: The authors of SLF4, LOG4J, and LOG4J2 are the same person

Modify the Mybatis configuration file. Note that if you use third-party dependencies, this setting does not need to be configured. It is also possible not to configure it here.

In fact, no configuration is required unless you use the built-in

Introduce jar package

Then introduce the xml configuration file necessary for logback

This configuration file must be called: logback.xml or logback-test.xml, not any other name.

This configuration file must be placed in the root directory of the class. It cannot be in other locations

logback.xml code

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定义⽇志⽂件的存储地址-->
    <property name="LOG_HOME" value="/home"/>
    <!-- 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示⽇期,%thread表示线程名,%-5level:级别从左显示5
           个字符宽度%msg:⽇志消息,%n是换⾏符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>
    <!-- 按照每天⽣成⽇志⽂件 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--⽇志⽂件输出的⽂件名-->
            <FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--⽇志⽂件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示⽇期,%thread表示线程名,%-5level:级别从左显示5
           个字符宽度%msg:⽇志消息,%n是换⾏符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logge
                r{50} - %msg%n</pattern>
        </encoder>
        <!--⽇志⽂件最⼤的⼤⼩-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>100MB</MaxFileSize>
        </triggeringPolicy>
    </appender>
    <!--mybatis log configure-->
    <logger name="com.apache.ibatis" level="TRACE"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>
    <!-- ⽇志输出级别,logback⽇志级别包括五个:TRACE < DEBUG < INFO < WARN < ERROR -->
    <root level="DEBUG">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>
</configuration>

test

 

Guess you like

Origin blog.csdn.net/tiantiantbtb/article/details/132741802