Home  >  Article  >  Java  >  What is Mybatis? Introduction to Mybatis related content

What is Mybatis? Introduction to Mybatis related content

不言
不言forward
2018-10-12 14:44:062797browse

This article brings you what is Mybatis? The introduction of Mybatis related content has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Introduction to MyBatis

MyBatis was originally an open source project iBatis of apache. In 2010, this project was moved from apache software foundation to google code and renamed MyBatis . Migrated to Github in November 2013.

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manual setting of parameters and retrieval of result sets. MyBatis can use simple XML or annotations for configuration and native Maps to map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) into records in the database.

MyBatis reference official website

http://www.mybatis.org/mybatis-3/zh/index.html

MyBatis download address

https://github.com/mybatis/mybatis-3

Advantages of MyBatis

  • Open source excellent persistence layer framework

  • Separation of SQL statements and code

  • Configuration-oriented programming

  • Good support for complex data mapping

  • Dynamic SQL

MyBatis development steps

1. Add the required jar package

1) mybatis-3.3.0 core package (if you need log operation, you can import dependent packages)

2) Database driver (mysql-connector-java-5.1.22-bin)

2. Create a database and add test data

create table `tal_employee` (
    `id` int (11),
    `last_name` varchar (360),
    `email` varchar (300),
    `gender` char (9)
);
INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('1','韩信','hanxin@gemail.com','男');
INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('2','LiBaihH','libai@gemail.com','男');
INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('3','孙尚香','sunshangxiang@gemail.com','女');
INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('4','安琪拉','anqila@gemail.com','女');
INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('5','Hello','Hello@gemail.com','男');
INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('6','Miya','Miya@gemail.com','男');
3. Create an entity class
public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    private String gender;
    //此处省略get set toString。。。
}
4. Create entity class mapping configuration file




    
    
5. Create mybatis main configuration file



    
    
        
        
            
            
            
            
                
                
                
                
            
        
    
    
    
        
    

Get SqlSessionFactory object

private SqlSessionFactory sqlSessionFactory;
    @Before
    public void init() throws IOException{
        //读取mybatis主配置文件
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        /**
         * 实例化SqlSessionFactory
         * 如果没有指定默认环境,可以在这里指定使用的环境ID,比如我先在有个DEV环境
         * sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"DEV");
         * 我这里已经使用了默认环境所以我就不用这种方式创建了
         */
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

Access the database

Get the SqlSession object, act on a conversation with the database, act on a conversation with the database

SqlSession session = sqlSessionFactory.openSession();

Get all employee records

EmployeeMapper is the namespace of our entity class mapping file, findAll is the ID of our select tag

List employees = session.selectList("EmployeeMapper.findAll");
        for (Employee employee : employees) {
            System.out.println(employee);
        }

Access results:

Employee [id=1, lastName=null, email=hanxin@gemail.com, gender=男]
Employee [id=2, lastName=null, email=libai@gemail.com, gender=男]
Employee [id=3, lastName=null, email=sunshangxiang@gemail.com, gender=女]
Employee [id=4, lastName=null, email=anqila@gemail.com, gender=女]
Employee [id=5, lastName=null, email=Hello@gemail.com, gender=男]
Employee [id=6, lastName=null, email=Miya@gemail.com, gender=男]

It is normal for us to access the database here, why is lastName empty? ?

Solution to the mismatch between table fields and class attribute names

Reason: It should be because the attribute on our entity class called lastName does not correspond to the name of the database column last_name, so it is obtained The value is empty

Solution 1: Alias ​​the select tag in the entity class mapping file

Solution 2: Configure camel case naming in the mybatis main configuration file, you need to The configuration is ranked first, otherwise an XML error will be reported


    
    

Use option 2 The attribute lastName in our class will match the database field last_name

Use the log to view SQL statements, etc.

First we need to add mybatis dependency package

Add log4j.properties

#设置输出级别和输出位置
log4j.rootLogger=debug,Console
#设置控制台相关的参数
log4j.appender.Console=org.apache.log4j.ConsoleAppender  
log4j.appender.Console.layout=org.apache.log4j.PatternLayout  
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  
#设置MyBatis的输出内容
log4j.logger.java.sql.ResultSet=INFO  
log4j.logger.org.apache=INFO  
log4j.logger.java.sql.Connection=DEBUG  
log4j.logger.java.sql.Statement=DEBUG  
log4j.logger.java.sql.PreparedStatement=DEBUG

So that we can use log4j to view our sql statements and incoming parameters. . Wait

MyBatis configuration file

  • Through the previous simple MyBatis case, you should understand the basic structure of the MyBatis framework, which is the same as Hibernate , MyBatis contains a core configuration file and mapping file.

  • Core configuration file (mybatis-config.xml): Contains the core configuration of Mybatis, including connection pool information, transactions, loading mapping files, parameter settings and other configurations.

  • Mapping file (EmployeeMapper.xml): It mainly implements the mapping of entity objects to the database, associations, Sql statements, etc.

Core configuration file

##Some external properties, these properties can be replacedThe extremely important adjustment settings in Mybatis will change the default behavior of Mybatis. Set an alias for the Java type, which is only related to xml configuration. Mapper, loads the MyBatis mapping file. Plug-in, Mybatis allows users to intercept at a certain point in the mapping.

环境配置

  1. Mybatis可以通过

    配置多种环境,比如开发环境、测试环境和生产环境等。

  2. 不过要记住,尽管可以配置多个环境,但是SqlSessionFactory对象只能加载一个。如果你需要同时连接多个数据库,需要创建多个SqlSessionFactory实例。

事务管理

在 MyBatis来进行事务的设置,其中有两种类型的事务管理器。

  1. JDBC:这个配置就是直接使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务范围。

  2. MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接,然而一些容器并不希望这样,因此需要将 closeConnection 属性设置为 false 来阻止它默认的关闭行为。


    

如果你正在使用 Spring + MyBatis,则没有必要配置事务管理器, 因为 Spring 模块会使用自带的管理器来覆盖前面的配置。

数据源

使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。有三种数据源类型

  1. UNPOOLED:这个数据源的实现只是每次被请求时打开和关闭连接。

  2. POOLED:这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来, 避免了创建新的连接实例时所必需的初始化和认证时间。

  3. JNDI:使用JNDI在外部配置数据源。

properties标签

properties为外部属性,比如数据库连接信息可以配置到一个单独的properties文件中,然后在xml中进行引入。

添加一个db.properties文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root

在mybatis主配置文件中引用



    
        
        
            
            
            
            
        
    

映射器

通常MyBatis中将映射关系(非必须)和SQL语句写入到映射文件中,在配置文件中需要手动进行加载映射文件。加载映射文件使用进行加载。Mybatis中有4种加载方式。

1.使用resource,加载classpath路径进行加载。


    

2.使用url路径进行加载。


    

3.使用calss进行加载,注解方式。



    

4.使用package进行加载,注解方式。



    

别名的使用

之前,我们在sql映射xml文件中的引用实体类时,resultType需要写上实体类的全类名(包名+类名),如下:

在mybatis主配置文件中加入


    

这样在resultType中就可以直接使用Employee类型了。这个别名是不区分大小写的。

TagDescription

Configuration environment





The above is the detailed content of What is Mybatis? Introduction to Mybatis related content. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete