1-Mybatis entry case

Resource: https://gitee.com/axinawang/study_mybatis.git

Reference: Dark Horse Programmer Issue 58

One, set up Mybatis development environment

1. Create a maven project, create a database and table, add log property files

Create the  mybatis01  project, the project information is as follows: Groupid :cn.oesoft ArtifactId :mybatis01 Packing :jar The sql files of the database and table are in the above resources Because MyBatis uses log4j to output log information by default, if you want to view the output SQL statement of the console, you need to configure its log file under the classpath path

# Set root category priority to INFO and its only appender to CONSOLE.#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatallog4j.rootCategory=debug, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE.log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout.log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppenderlog4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayoutlog4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout.log4j.appender.LOGFILE=org.apache.log4j.FileAppenderlog4j.appender.LOGFILE.File=d:\axis.loglog4j.appender.LOGFILE.Append=truelog4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayoutlog4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n 

2. Add the coordinates of Mybatis 3.4.5     Add the coordinates of Mybatis3.4.5 in the pom.xml   file   , as follows:

    <dependencies>        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>3.4.5</version>        </dependency>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>4.10</version>            <scope>test</scope>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>5.1.6</version>            <scope>runtime</scope>        </dependency>        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>1.2.12</version>        </dependency>        <dependency>            <groupId>org.projectlombok</groupId>            <artifactId>lombok</artifactId>            <version>RELEASE</version>            <scope>compile</scope>        </dependency>    </dependencies>

3. Write the User entity class

/** * @ClassName: User * @Author: linxin * @Date: 2021/6/7 15:29 * @Company: http://www.oesoft.cn * @Description: 用户的实体类 */@Datapublic class User {    private Integer id;    private String username;    private Date birthday;    private String sex;    private String address;     }

4. Write the persistence layer interface IUserDao

/** * @ClassName: IUserDao * @Author: linxin * @Date: 2021/6/7 15:36 * @Company: http://www.oesoft.cn * @Description: IUserDao 接口就是我们的持久层接口(也可以写成 UserDao 或者 UserMapper) */public interface IUserDao {    /**     * @description: 查询所有用户     * @date: 2021/6/7 15:37      */    List<User> findAll();}

5. Write the mapping file IUserDao.xml for the persistence layer interface    Claim:             Creation location:    Must be in the same package as the persistence layer interface.             Name: The    file name must be named after the persistence layer interface name, and the extension is    .xml

<?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="cn.oesoft.mybatis01.dao.IUserDao">    <!--配置查询所有操作-->    <select id="findAll" resultType="cn.oesoft.mybatis01.domain.User">        select * from user    </select></mapper>

6. Write the SqlMapConfig.xml configuration 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"><!-- mybatis的主配置文件 --><configuration>    <!-- 配置环境 -->    <environments default="mysql">        <!-- 配置mysql的环境-->        <environment id="mysql">            <!-- 配置事务的类型-->            <transactionManager type="JDBC"></transactionManager>            <!-- 配置数据源(连接池) -->            <dataSource type="POOLED">                <!-- 配置连接数据库的4个基本信息 -->                <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="root"/>            </dataSource>        </environment>    </environments>    <!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->    <mappers>        <mapper resource="cn/oesoft/mybatis01/dao/IUserDao.xml"/>    </mappers></configuration>

7. Write the test class

/** * @ClassName: UserDaoTest * @Author: linxin * @Date: 2021/6/7 16:10 * @Company: http://www.oesoft.cn * @Description: TODO */public class UserDaoTest {    @Test    public void findAllTest() throws Exception{        //1.读取配置文件        InputStream in= Resources.getResourceAsStream("SqlMapConfig.xml");        // 2.创建SqlSessionFactory的构建者对象        SqlSessionFactoryBuilder builder= new SqlSessionFactoryBuilder();        //3.使用构建者创建工厂对象SqlSessionFactory        SqlSessionFactory factory= builder.build(in);        // 4.使用SqlSessionFactory生产SqlSession对象        SqlSession session= factory.openSession();        // 5.使用SqlSession创建dao接口的代理对象        IUserDao userDao= session.getMapper(IUserDao.class);        //6.使用代理对象执行查询所有方法        List<User> users= userDao.findAll();for(User user: users) {System.out.println(user);}        //7.释放资源        session.close();        in.close();    }}

8. Annotation-based use of mybatis

a. Modify SqlMapConfig.xml

删除<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->    <mappers>        <mapper resource="cn/oesoft/mybatis01/dao/IUserDao.xml"/>    </mappers>添加<!-- 告知 mybatis 映射配置的位置 -->    <mappers>        <mapper class="cn.oesoft.mybatis01.dao.IUserDao"/>    </mappers>​

b. Delete the mapping file IUserDao.xml

c. Add annotations to the persistence layer interface

public interface IUserDao {    /**     * @description: 查询所有用户     * @date: 2021/6/7 15:37      */    @Select("select * from user")    List<User> findAll();}