MyBatis-study notes 02 [02. Mybatis entry case]

  1. MyBatis-study notes 01 [01. Mybatis course introduction and environment construction] [day01]
  2. MyBatis-study notes 02 [02. Mybatis entry case]
  3. MyBatis-study notes 03 [03. Customize Mybatis framework]
  4. MyBatis-study notes 04 [04. Custom Mybatis framework based on annotation development]
  5. MyBatis-study notes 05 [05. Use Mybatis to complete CRUD]
  6. MyBatis-study notes 06 [06. Use Mybatis to complete the development of the DAO layer]
  7. ​​​​​​​MyBatis-study notes 07 [07.Mybatis connection pool and transaction]
  8. ​​​​​​​MyBatis-study notes 08 [08. Dynamic SQL]
  9. ​​​​​​​MyBatis-study notes 09【09.Multi-table operation of Mybatis】
  10. ​​​​​​​MyBatis-study notes 10 [10. JNDI extended knowledge]
  11. ​​​​​​​MyBatis-study notes 11 [11. Mybatis cache]
  12. ​​​​​​​MyBatis-study notes 12 [12. Mybatis annotation development]

table of Contents

1 Getting started with mybatis

Import log4j.properties under the resources folder

Create test class

2 Design pattern analysis in the mybatis entry case

3 Mybatis annotation development and the way to write dao implementation classes

Use of annotations

Annotation configuration

MyBatis uses dao to implement classes

Structure chart

UserDaoImpl.java

MybatisTest.java


1 Getting started with mybatis

Import log4j.properties under the resources folder

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.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.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.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.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

Create test class

package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
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.InputStream;
import java.util.List;

/**
 * mybatis的入门案例
 */
public class MyBatisTest {
    /**
     * 入门案例
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        //1.读取配置文件 加载文件中的信息
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产SqlSession对象
        SqlSession session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
        //6.释放资源
        session.close();
        in.close();
    }
}

2 Design pattern analysis in the mybatis entry case

The advantage of creating one more class at a time: flexible encapsulation, allowing developers to have more choices when applying.

Note: In this section, the teacher talked about this set of codes! The analysis is very detailed, the paper notes are not very detailed!

Analysis of introductory cases

3 Mybatis annotation development and the way to write dao implementation classes

Mybatis entry case
        Step 1: Read the configuration file
        Step 2: Create a SqlSessionFactory factory
        Step 3: Create SqlSession
        Step 4: Create a proxy object of the Dao interface
        Step 5: Execute the method in Dao Step
        6: Release resources

        Note:
            Don’t forget the way to tell mybatis which entity class to encapsulate in the mapping configuration
            : specify the fully qualified class name of the entity class resultType="com.itheima.domain.User"
        
        Mybatis annotation-based entry case:
            put IUserDao .xml removed, use the @Select annotation on the method of the dao interface, and specify the SQL statement
            and need to configure the mapper in SqlMapConfig.xml at the same time, use the class attribute to specify the fully qualified class name of the dao interface.
Clear: In
        our actual development, the simpler the better, so we all adopt the way of not writing dao implementation classes.
        Regardless of the use of XML or annotation configuration.
        But Mybatis supports writing dao implementation classes.

Use of annotations

day01_eesy_02mybatis_ennotation

Annotation configuration

MyBatis uses dao to implement classes

The successful query result diagram of the dao implementation class:

Structure chart

UserDaoImpl.java

package com.itheima.dao.impl;

import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UserDaoImpl implements IUserDao {
    private SqlSessionFactory factory;

    public UserDaoImpl(SqlSessionFactory factory) { // 更改默认构造函数
        this.factory = factory; // 使用factory得到session
    }

    public List<User> findAll() {
        //1.使用工厂创建SqlSession对象
        SqlSession session = factory.openSession(); // 使用factory得到session
        //2.使用session执行查询所有用户的方法
        List<User> users = session.selectList("com.itheima.dao.IUserDao.findAll");//通过配置拿到sql语句
        session.close();
        //3.返回查询结果
        return users;
    }
}

MybatisTest.java

package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.dao.impl.UserDaoImpl;
import com.itheima.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

/**
 * mybatis的入门案例
 */
public class MybatisTest {
    /**
     * 入门案例
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂创建dao对象
        IUserDao userDao = new UserDaoImpl(factory);
        //4.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
        //5.释放资源
        in.close();
    }
}

Only by doing the present work well can we dream about the future, focus on the things in front of us, and fall into endless worries about the things that have not happened yet, which will not help things, but will be troublesome for ourselves.

Guess you like

Origin blog.csdn.net/weixin_44949135/article/details/114330969