IDEA uses maven to load myBatis (nanny-level multi-map)

Nanny-level graphics and text full-process configuration

In this article, the usage recommended by the official website of mybatis is used, which is interface-oriented, and it is more convenient to operate mybatis. Another method will not be discussed here.

create project

Create a new project without using the maven template. After
Do not use maven templates
filling in the project name and GroupId
insert image description here
, some files and directories have been generated in IDEA, and the maven pom
new construction
. Became IDEA's maven

View maven used by IDEA

create submodel

You can delete the src directory and create a new submodule. By default,
create submodule
the submodule created by default has automatically written the parent tag

parent tag

Configure the maven dependency of mybatis

In the pom.xml file of mavenDemo, write mybatis, mysql driver (note that the driver version must match the database you use) and the dependencies of junit. You can manually go
to the mvn website to check how to write maven dependencies and put them in the link: https://mvnrepository.com/

	<dependencies>
        <!--   mybatis     -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <!--   mysql     -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.13</version>
        </dependency>

        <!--   junit     -->
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Create a mybatis configuration file under the resource directory resource under the untitled module: mybatis-config.xml
insert image description here
simply fill in the database information

<?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://127.0.0.1:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="toor"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

It's almost a billion points away from this shelf and it's over

write a demo

When writing the demo, you still need to set up a shelf.
Create three packages dao, pojo, and utils in the java folder under the src directory

Create a tool class MyBatisUtil under the utils packagePackage structure and MyBatisUtil.java

package xyz.baochao.utils;

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.InputStream;

public class MyBatisUtil {
    
    

    //提升SqlSessionFactory作用域
    private static SqlSessionFactory sqlSessionFactory;
    static{
    
    
        try {
    
    
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

    //方便我们直接获取SqlSession
    public static SqlSession getSqlSession(){
    
    
        return sqlSessionFactory.openSession();
    }
}

Create a table in the database for testing later

CREATE TABLE users(
	u_id INT(20) PRIMARY KEY,
	u_name char(20),
	u_pwd char(20)
);

INSERT INTO users(u_id,u_name,u_pwd) VALUES
(1,'zs',123456),
(2,'ls',456789),
(3,'ww',789123);

Because mybatis uses the entity class when passing values, so at this time, a User class that can correspond to the database user should be prepared and placed under the pojo package

There are three member variables in the User class. IDEA automatically generates get and set methods, and then a toString method. The construction method defaults to no parameter construction. Touching
IDEA, freeing your hands, it will be better when you can write your own code
Entity class User

Create an interface under the dao package, let’s call it UserDao, it’s perfect, and in the future, it will be interface-oriented, and one method will solve all troubles!

package xyz.baochao.dao;

import xyz.baochao.pojo.User;

import java.util.List;

public interface UserDao {
    
    
    //查询所有用户数据
    List<User> getAll();
}

Key a UserMapper.xml next to it, and all sql statements will be written in it in the future, decoupling! Wonderful!

<?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="xyz.baochao.dao.UserDao">
    <!-- id 接口里的方法名  resultType 返回值类型指向User类 -->
    <select id="getAll" resultType="xyz.baochao.pojo.User">
        select * from users
    </select>
</mapper>

Write in the mybatis-config.xml file:

<!-- 把刚才是UserMapper.xml文件加载进mybatis主配置文件 -->
    <mappers>
        <mapper resource="xyz/baochao/dao/UserMapper.xml" />
    </mappers>

At this point the directory structure should look like this:
Directory Structure

There is another very important thing before testing, which is maven's resource filtering! ! !
Configure all the two pom.xml files

	<build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

Well, all the construction is completed at this time, let's test and test!

carry out testing

Create a new test class under the test package. The package name is the same as that under the java folder above. The class name is UserDaoTest, which is convenient for management.

UserDaoTest

package xyz.baochao.dao;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import xyz.baochao.pojo.User;
import xyz.baochao.utils.MyBatisUtil;

import java.util.List;

public class UserDaoTest {
    
    
    @Test
    public void test(){
    
    
        //使用工具类获取SqlSession
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        //把接口加载进来
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        //取出数据库中的所有数据放入集合
        List<User> userList = userDao.getAll();
        //遍历集合输出内容
        for (User user : userList) {
    
    
            System.out.println("user = " + user);
        }
        //关闭SqlSession
        sqlSession.close();
    }
}

Test it out:

The first time I actually reported an error, reported ExceptionInInitializerError, checked it, the resource filter is correct, just when I was at a loss, I suddenly found that I wrote a Chinese comment in the xml configuration file, and then looked at the character encoding:

<?xml version="1.0" encoding="UTF-8"?>

Good guy, the character encoding problem, remove the "-" in the middle of utf-8, this is the little horizontal bar

<?xml version="1.0" encoding="UTF8"?>

After the change, take a wave of tests!

test results

Everything is normal, and the building process seems troublesome, but in fact, I don’t know how many times more comfortable than jdbc manual code, I took a long breath and said to IDEA: "IDEA, you are already a mature tool, you should be able to I went to change the abnormality myself..."

Guess you like

Origin blog.csdn.net/qq_39950529/article/details/117170928