Spring Integrate Mybatis -- Spring Quick Start Nanny-Level Tutorial (4)


foreword

In order to consolidate the knowledge learned, the author tried to start publishing some blogs of learning notes for future review. Of course, it would be great if it could help some newcomers learn new technologies. The author is a piece of food. If there are any mistakes in the records in the article, readers and friends are welcome to criticize and correct.
(The reference source code of the blog can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)

5. Spring integrates Mybatis

1. Mybatis general development process

  1. Design and create database table tbl_account
  • Example of table creation query statement
create database spring_db;
use spring_db;

drop table if exists tbl_account;

create table tbl_account(
	id int primary key auto_increment,
	name varchar(20),
	account varchar(20)
);

INSERT INTO tbl_account VALUES (1, 'Tom', 1000);
INSERT INTO tbl_account VALUES (2, 'Jerry', 500);

  • Effect

insert image description here

  1. Create the corresponding maven module and import the corresponding coordinates in pom.xml
 <dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.6</version>
 </dependency>

 <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
 </dependency>
  1. Create the corresponding entity class Account
public class Account implements Serializable {
    
    
    //此处省略getter、setter和toString方法
    private Integer id;
    private String name;
    private Double money;
    
}
  1. Create mybatis core configuration file mybatis-config.xml
<?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>
    <properties resource="jdbc.properties"></properties>
    
    <typeAliases>
        <package name="com.itheima.domain"/>
    </typeAliases>
    
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.username}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <package name="org.example.dao"></package>
    </mappers>
</configuration>

  1. Create database table information jdbc.properties
 jdbc.driver=com.mysql.jdbc.Driver
 jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
 jdbc.username=root
 jdbc.password=root
 
  1. Create and write the mapper proxy interface AccountDao in the form of annotations (or an interface corresponding to a mapper file)
public interface AccountDao {
    
    

    @Insert("insert into tbl_account(name,money)values(#{name},#{money})")
    void save(Account account);

    @Delete("delete from tbl_account where id = #{id} ")
    void delete(Integer id);

    @Update("update tbl_account set name = #{name} , money = #{money} where id = #{id} ")
    void update(Account account);

    @Select("select * from tbl_account")
    List<Account> findAll();

    @Select("select * from tbl_account where id = #{id} ")
    Account findById(Integer id);
}
  1. Create a mock test app
public class App {
    
    
    public static void main(String[] args) throws IOException {
    
    
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        // 3. 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        // 4. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 5. 执行SqlSession对象执行查询,获取结果User
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);

        Account ac = accountDao.findById(1);
        System.out.println(ac);

        // 6. 释放资源
        sqlSession.close();
    }
}

  1. Simulation test class running results

insert image description here

  1. File Structure Reference

insert image description here

2. Spring integration mybatis thinking analysis

  1. We know that one of the characteristics of spring is the ability to manage beans, so which beans in mybatis need to be managed by spring? We can divide the sample running program APP of mybatis into the following parts. Through observation, we can find that there are mainly the following objects: SqlSessionFactorySqlSessionAccountDao

insert image description here

  • Although AccountDao directly executes business, it is not the root object, and the objects created are different with different business requirements, so it is not the core object.
  • The SqlSession object is created by the factory, similar to the connection pool, the object has actually been created
  • So the core object is SqlSessionFactory
  1. By observing the core configuration file of Mybatis, we can divide it into the following parts:

insert image description here

  • The role of the first part is to configure and load database information. The difference is whether the loaded information is obtained in this configuration file, which has nothing to do with SqlSessionFactory
  • The function of the second part is to configure the type of data obtained after the operation of Mybatis, which is an optional attribute in the SqlSessionFactory object
  • The part in the third part of the dataSourcre tag is the database connection information, which is necessary. Without this content, SqlSessionFactory cannot know the database information of the operation
  • The third part of the transactionManager tag is related to transaction processing, which is also related to SqlSessionFactory. This blog will not discuss it for the time being.
  • The fourth part is related to business operations, even if not, SqlSessionFactory can also be created. But in actual development, if you need to use Mapper agent development, you need to configure this part of the content.
  1. summary

In summary, the core object in mybatis that spring should focus on managing is SqlSessionFactory. Using Spring to create SqlSessionFactory objects and business-related Mapper mapping objects is our main goal.

3. Spring integrates Mybatis environment preparation (annotation development)

  1. Import spring development-related coordinates in the pom.xml file
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.16</version>
    </dependency>

<!--spring操作数据库-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

<!--spring整合mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
  1. Create Spring core configuration class SpringConfig
 @Configuration
 @ComponentScan("org.example")

 public class SpringConfig {
    
    
 }

  1. Create business interface AccountService
public interface AccountService {
    
    

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List<Account> findAll();

    Account findById(Integer id);

}

  1. Create the corresponding implementation class AccountServiceImpl
@Service
public class AccountServiceImpl implements AccountService {
    
    

    @Autowired
    private AccountDao accountDao;

    public void save(Account account) {
    
    
        accountDao.save(account);
    }

    public void update(Account account){
    
    
        accountDao.update(account);
    }

    public void delete(Integer id) {
    
    
        accountDao.delete(id);
    }

    public Account findById(Integer id) {
    
    
        return accountDao.findById(id);
    }

    public List<Account> findAll() {
    
    
        return accountDao.findAll();
    }
}

  1. database connection information
  • Create database information configuration class JdbcConfig
public class JdbcConfig {
    
    
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource dataSource(){
    
    
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(userName);
        ds.setPassword(password);
        return ds;
    }
}
  • Load database information properties file
@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
    
    
}

  • Load database information configuration class

Method 1: Add @Configuration to the core configuration class, and scan through the @ComponentScan annotation in the Spring core configuration class SpringConfig

Method 2: Manual import

@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
@Import(JdbcConfig.class)
public class SpringConfig {
    
    
}
  1. File structure preview

insert image description here

4. Spring integrates Mybatis

  1. MybatisConfig configuration class
  • Create the Mybatis configuration class MybatisConfig (achieve the goal: create SqlSessionFactoryBean)
public class MybatisConfig {
    
    
    //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
    
    
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        //设置别名
        ssfb.setTypeAliasesPackage("org.example.domain");
        //配置数据源
        ssfb.setDataSource(dataSource);
        return ssfb;
    }

    //定义bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
    
    
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("org.example.dao");
        return msc;
    }

}




  • Load Mybatis configuration class
@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
@Import({
    
    JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
    
    
}

  1. Create a mock test class
public class App2 {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        AccountService accountService = ctx.getBean(AccountService.class);

        Account ac = accountService.findById(1);
        System.out.println(ac);
    }
}

  1. operation result

insert image description here
4. File structure preview

insert image description here

5. Summary

Simply put, Spring's integration of Mybatis is based on the development of Spring with an additional MyBatisConfig configuration file

insert image description here
insert image description here

Summarize

Everyone is welcome to leave a message for exchange and criticism. If the article is helpful to you or you think the author's writing is not bad, you can click to follow, like, and bookmark to support.
(The reference source code of the blog can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)

Guess you like

Origin blog.csdn.net/HHX_01/article/details/130748776