MyBatis Introduction (i)

Source: Internet
Author: User
Tags log4j

Directory

    • MyBatis Getting Started
      • MyBatis Introduction
      • Advantages of MyBatis
      • MyBatis Development Steps
      • Get Sqlsessionfactory Object
      • Accessing the database
      • Resolving table fields does not correspond to class property names
      • Use logs to view SQL statements, etc.
      • Configuration file for MyBatis
        • Core configuration Files
        • Environment configuration
        • Transaction management
        • Data source
        • Properties tab
        • Mapper
        • Use of aliases
MyBatis Getting Started

Editor:simplewu

MyBatis Introduction
    • MyBatis is an open source project for Apache Ibatis, which was migrated to Google code by the Apache Software Foundation in 2010 and renamed MyBatis. Migrated to GitHub in November 2013.
    • MyBatis is an excellent persistence layer framework that supports the customization of SQL, stored procedures, and advanced mapping. MyBatis avoids almost all JDBC code and manually sets parameters and gets the result set. 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) to records in a database.

MyBatis Reference website

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

MyBatis

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

Advantages of MyBatis
    • Open source Excellent persistence layer Framework
    • Separating SQL statements from 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 Pack (can import dependent packages if log operations are required)

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),    
INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('1','韩信','[email protected]','男');INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('2','LiBaihH','[email protected]','男');INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('3','孙尚香','[email protected]','女');INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('4','安琪拉','[email protected]','女');INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('5','Hello','[email protected]','男');INSERT INTO `tal_employee` (`id`, `last_name`, `email`, `gender`) VALUES('6','Miya','[email protected]','男');
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 an Entity class mapping profile
<?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="EmployeeMapper">    <!-- 定义一个查询方法  resultType 返回值类型-->    <select id="findAll" resultType="com.simple.mybatis.entitys.Employee">        select * from tal_employee    </select></mapper>
5. Create a mybatis master 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" > <configuration> <!--configuration environment default uses environment name---<environments default= "Development" > <!-- Configure an environment--<environment id= "Development" > <!--Using transaction JDBC transaction Manager--<transacti Onmanager type= "JDBC"/> <!--configuration database connection-<datasource type= "Pooled" > & Lt;property name= "Driver" value= "Com.mysql.jdbc.Driver"/> <property name= "url" value= "jdbc:mysql://l Ocalhost:3306/mybatis "/> <property name=" username "value=" root "/> <property na Me= "Password" value= "root"/> </dataSource> </environment> </environments> &l t;! --Load Map--<mappers> <mapper resource= "Com/simple/mybatis/entitys/employeemappEr.xml "/> </mappers></configuration> 

Write code See below

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);    }
Accessing the database

Gets the Sqlsession object that is used for a session with the database to respond to the database once

SqlSession session = sqlSessionFactory.openSession();

Get all Employee records

Employeemapper is the namespace of our entity class mapping file, and FindAll is the ID of our select tag.

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

Access results:

Employee [id=1, lastName=null, [email protected], gender=男]Employee [id=2, lastName=null, [email protected], gender=男]Employee [id=3, lastName=null, [email protected], gender=女]Employee [id=4, lastName=null, [email protected], gender=女]Employee [id=5, lastName=null, [email protected], gender=男]Employee [id=6, lastName=null, [email protected], gender=男]

Here we access the database is normal, why LastName is empty?

Resolving table fields does not correspond to class property names

Cause: It should be for us the attribute on the entity class is called LastName and the database column Last_Name name does not correspond so the obtained value is empty

Solution 1: Take an alias from the select tag in the entity class map file

<select id="findAll" resultType="com.simple.mybatis.entitys.Employee">        select id,last_name AS lastName,email,gender from tal_employee</select>

Solution 2: Configure Camel-named in the MyBatis master configuration file, you need to queue the configuration before the XML error

<settings>    <!-- 开启驼峰式命名规则 -->    <setting name="mapUnderscoreToCamelCase" value="true"/></settings>

Using scenario 2, the attribute LastName in our class matches the database field last_name

Use logs to view SQL statements, etc.

First we need to add the 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 we can use log4j to see our SQL statements, the arguments passed in. Wait a minute

Configuration file for MyBatis
    • With the simple MyBatis case above, you should understand the basic structure of the MyBatis framework, and like Hibernate, MyBatis contains a core configuration file and a mapping file.
    • Core configuration file (Mybatis-config.xml): Contains the core configuration of the MyBatis, including connection pool information, transactions, load mapping files, parameter settings and other configurations.
    • Mapping file (Employeemapper.xml): The main implementation of the entity object to the database Mapping, association, SQL statements and so on.
Core configuration Files
label Description
Configuring the Environment
Some external properties, these properties can be replaced
The most important adjustment setting in MyBatis will change the default behavior of MyBatis.
Set an alias for the Java type, which is only relevant to the XML configuration.
Mapper that loads the MyBatis mapping file.
Plugin, MyBatis allows the user to intercept at some point in the map.
Environment configuration
    1. MyBatis can be configured in a variety of environments, such as development environments, test environments, and production environments.
    2. Remember, though, that although you can configure multiple environments, the Sqlsessionfactory object can only load one. If you need to connect multiple databases at the same time, you need to create multiple sqlsessionfactory instances.
Transaction management

In MyBatis , there are two types of transaction managers that are set up for transactions.

    1. JDBC: This configuration is the direct use of the JDBC Commit and rollback settings, which depend on the connection from the data source to manage the transaction scope.
    2. MANAGED: This configuration hardly does anything. It never commits or rolls back a connection, but instead lets the container manage the entire life cycle of the transaction (such as the context of the JEE application server). It closes the connection by default, but some containers do not want it, so you need to set the CloseConnection property to False to prevent it from shutting down by default.
<transactionManager type="MANAGED">    <property name="closeConnection" value="false"/></transactionManager>

If you are using Spring + MyBatis, it is not necessary to configure the transaction manager because the Spring module uses its own manager to overwrite the previous configuration.

Data source

Use the standard JDBC data source interface to configure resources for the JDBC Connection object. There are three types of data sources

    1. Unpooled: The implementation of this data source only opens and closes the connection each time it is requested.
    2. Pooled: This data source implementation uses the concept of "pooling" to organize JDBC connection objects, avoiding the initialization and authentication time required to create a new connection instance.
    3. Jndi: Use Jndi to configure the data source externally.
Properties tab

Properties are external attributes, such as database connection information that can be configured into a single properties file and then introduced in XML.

Add a db.properties file

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/testusername=rootpassword=root

Referencing in the MyBatis master configuration file

<properties resource="db.properties" /><environments default="development">    <environment id="development">        <transactionManager type="JDBC" />        <dataSource type="POOLED">            <property name="driver" value="${driver}" />            <property name="url" value="${url}" />            <property name="username" value="${username}" />            <property name="password" value="${password}" />        </dataSource>    </environment></environments>
Mapper

Mapping relationships (non-mandatory) and SQL statements are usually written to the mapping file in MyBatis, and the mapping file needs to be manually loaded in the configuration file. Load the mapping file using to load. There are 4 modes of loading in the MyBatis.

1. Load the classpath path using resource.

<mappers>    <mapper resource="com/simple/mybatis/entitys/EmployeeMapper.xml"/></mappers>

2. Load using a URL path.

<mappers>    <mapper url="file:///var/mappers/AuthorMapper.xml"/></mappers>

3. Use CALSS to load, annotate the method.

<!– 加载class类--><mappers>    <mapper class="使用注解的全类名"/></mappers>

4. Use the package to load and annotate the method.

<!– 加载某个包下的所有class文件--><mappers>    <package name="com.simple.mybatis.entitys"/></mappers>
Use of aliases

Previously, when we referenced entity classes in the SQL mapping XML file, Resulttype needed to write the full class name of the entity class (package name + class name), as follows:

<select id="findAll" resultType="com.simple.mybatis.entitys.Employee">        select id,last_name AS lastName,email,gender from tal_employee</select>

In the MyBatis master configuration file , add

<typeAliases>    <typeAlias type=“com.simple.mybatis.entitys.Employee" alias="Employee"/></typeAliases>

This allows you to use the employee type directly in the Resulttype. This alias is not case-sensitive.

MyBatis Introduction (i)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.