MyBatis is easy to use and get started.

Source: Internet
Author: User

MyBatis is easy to use and get started.

This article records some errors and simple understandings encountered when Mybatis is used for the first time. The example is the JAVA project in Eclipse and the database connection is defined using XML files.

 

You can use Java JDBC APIs to directly operate databases. However, the framework is more convenient and efficient, and some powerful functions (such as transaction management) provided by the framework can also be used ), and Mybatis is such a framework.

Mybatis consists of four parts:

① SqlSessionFactoryBuilder

② SqlSessionFactory

③ SqlSession

④ SQL Mapper

To access (operate) A database: to establish a database connection, you must define the database operation method (insert/update/delete ...), you must have specific SQL statements for operating tables in the database. SqlSessionFactoryBuilder, SqlSessionFactory, and SqlSession are used to establish database connections, manage connections, and release connections at the underlying layer. For the business layer, you are concerned about defining an SQL statement so that Mybatis can conveniently present the results after executing the SQL statement to the user, which can be completed through SQL Mapper.

The SQL Mapper consists of two parts: JAVA interface, which defines the operations performed on the database at the business layer, and XML configuration file, defines specific database operation statements and ing rules.

Assume that the t_role and t_role tables in the test database have three fields: id, role_name, and note.

+ ----------- + ------------- + ------ + ----- + --------- + ---------------- +
| Field | Type | Null | Key | Default | Extra |
+ ----------- + ------------- + ------ + ----- + --------- + ---------------- +
| Id | bigint (20) | NO | PRI | NULL | auto_increment |
| Role_name | varchar (20) | YES | NULL |
| Note | varchar (20) | YES | NULL |
+ ----------- + ------------- + ------ + ----- + --------- + ---------------- +

The POJO class corresponding to the table is as follows:

package chapter2.pojo;public class Role {    private Long id;    private String roleName;    private String note;    public Long getId() {        return id;    }    public void setId(Long id) {        this.id = id;    }    public String getRoleName() {        return roleName;    }    public void setRoleName(String roleName) {        this.roleName = roleName;    }    public String getNote() {        return note;    }    public void setNote(String note) {        this.note = note;    }        @Override    public String toString() {        return "id:" + id + ", roleName:" + roleName + ", note:" + note;    }}
View Code

 

Some operations defined in the JAVA interface are as follows:

package chapter2.mapper;
import java.util.List;import java.util.Map;import chapter2.pojo.Role;public interface RoleMapper { public Role getRole(Long id); public int deleteRole(Long id); public int insertRole(Role role); public List<Role> findRoleByMap(Map<String, String> params);}

 

Corresponding to this interface, the configuration file RoleMapper. xml of the specific operation database is defined as follows:

<? Xml version = "1.0" encoding = "UTF-8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" chapter2.mapper. roleMapper "> <resultMap type =" chapter2.pojo. role "id =" roleMap "> <id property =" id "column =" id "/> <! -- Primary key --> <result property = "roleName" column = "role_name"/> <! -- Ing relationship of common columns --> <result property = "note" column = "note"/> </resultMap> <select id = "getRole" parameterType = "long" resultType = "Role"> select id, role_name as roleName, note from t_role where id =#{ id} </select> <insert id = "insertRole" parameterType = "Role"> insert into t_role (role_name, note) values (# {roleName}, # {note }) </insert> <delete id = "deleteRole" parameterType = "long"> delete from t_role where id =#{ id} </delete> <select id = "findRoleByMap" parameterType = "map" resultMap = "roleMap"> select id, role_name, note from t_role where role_name like concat ('%', # {roleName}, '%') and note like concat ('%', # {note }, '%') </select> </mapper>

 

Then, you can use SqlSessionFactory to create a SqlSession, SqlSession to obtain the corresponding RoleMapper instance, and then use the RoleMapper instance to call the method defined in the RoleMapper interface. In the end, Mybatis will follow the RoleMapper. the xml configuration file maps methods to specific database operation statements and finally accesses the database.

Use SqlSessionFactoryBuilder to create SqlSessionFactory Based on the dataSource configured in mybatisConfig. xml, and then use SqlSessionFactory to create SqlSession. The Code is as follows:

package chapter2.util;import java.io.IOException;import java.io.InputStream;import java.util.logging.Level;import java.util.logging.Logger;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class SqlSessionFactoryUtil {    private static SqlSessionFactory sqlSessionFactory = null;    private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class;    private SqlSessionFactoryUtil() {}        public static SqlSessionFactory initSqlSessionFactory() {        String resource = "mybatisConfig.xml";        InputStream inputStream = null;        try {            inputStream = Resources.getResourceAsStream(resource);        }catch(IOException ex) {            Logger.getLogger(SqlSessionFactoryUtil.class.getName()).log(Level.SEVERE, null, ex);        }        synchronized (CLASS_LOCK) {            if(sqlSessionFactory == null) {                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);            }        }        return sqlSessionFactory;    }        public static SqlSession openSqlSession() {        if(sqlSessionFactory == null)        {            initSqlSessionFactory();        }        return sqlSessionFactory.openSession();    }}
View Code

 

The user program obtains RoleMapper (row 20th) based on SqlSession, and then calls the method defined in it to operate the database. It can be seen from here that,You only need to define interfaces and define SQL operation statements in the XML configuration file to access the database.The Code is as follows:

Package chapter2.main; import java. io. IOException; import java. util. hashMap; import java. util. list; import java. util. map; import org. apache. ibatis. session. sqlSession; import chapter2.mapper. roleMapper; import chapter2.pojo. role; import chapter2.util. sqlSessionFactoryUtil; public class Chapter2Main {public static void main (String [] args) throws IOException {SqlSession sqlSession = null; try {sqlSession = S QlSessionFactoryUtil. openSqlSession (); RoleMapper roleMapper = sqlSession. getMapper (RoleMapper. class); Role role = new Role (); role. setRoleName ("testName"); role. setNote ("testNote"); roleMapper. insertRole (role); // roleMapper. deleteRole (1L); sqlSession. commit (); Map <String, String> paramsMap = new HashMap <> (); paramsMap. put ("roleName", "me"); paramsMap. put ("note", "no"); // with # {note} # {roleNam in the SQL statement E} consistent List <Role> result = roleMapper. findRoleByMap (paramsMap); for (Role role2: result) {System. out. println (role2) ;}} catch (Exception e) {System. out. println (e); sqlSession. rollback ();} finally {if (sqlSession! = Null) sqlSession. close ();}}}
View Code

 

Mybatis configure database connection: mybatisConfig. xml

 1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"     3 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 4 <configuration> 5     <properties resource="jdbc.properties"> 6     </properties> 7     <typeAliases> 8         <typeAlias alias="Role" type="chapter2.pojo.Role" /> 9     </typeAliases>10 11     <environments default="development">12         <environment id="development">13             <transactionManager type="JDBC">14                 <property name="autoCommit" value="false" />15             </transactionManager>16             <dataSource type="POOLED">17                 <property name="driver" value="${driver}" />18                 <property name="url" value="${url}" />19                 <property name="username" value="${username}" />20                 <property name="password" value="${password}" />21             </dataSource>22         </environment>23     </environments>24 25     <mappers>26         <mapper resource="chapter2\mapper\RoleMapper.xml" />27     </mappers>28 </configuration>

The XML configuration file of Mybatis defines many configuration tags, such as <configuration> <properties> <settings> <typeAliases>.

These labels have hierarchies and cannot be disordered. For example, the <properties> label should be placed before the <typeAliases> label.

The above 5th rows <properties> label is passedResource specifies an external jdbc configuration fileIn this way, when you configure the data source in lines 16-21, you can use variables to reference the values defined in the external jdbc configuration file, so that you can easily switch the database configuration.

The external jdbc configuration file is as follows:

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

 

The following describes the relationship between the XML configuration file RoleMapper. xml of the operating database and the RoleMapper and the RoleMapper of the pojo class:

The getRole method defined in the RoleMapper interface:

public Role getRole(Long id);

 

The SQL statement corresponding to this method in the RoleMapper. xml configuration file:

    <select id="getRole" parameterType="long" resultType="Role">        select id, role_name as roleName, note from t_role where id = #{id}    </select>

Id is used to uniquely identify the select statement. It is combined with the content of the <mapper namespace> label in RoleMapper. xml and uniquely identifies this select operation statement.ResultType = "Role" and "Role" are aliases defined in mybatisConfig. xml.

<Mapper namespace = "chapter2.mapper. roleMapper "> public Role getRole (Long id ); <select id = "getRole" parameterType = "long" resultType = "Role"> the value of id getRole is the getRole method name defined in the RoleMapper interface. parameterType is the parameter type of the getRole method. the result returned after the SQL statement is executed, encapsulate the result into the Role type of the POJO class --- this is also the return type of the getRole method. The method parameters are passed to # {id}

 

FindRoleByMap method defined in RoleMapper

    public List<Role> findRoleByMap(Map<String, String> params);
    <select id="findRoleByMap" parameterType="map" resultMap="roleMap">        select id,role_name,note from t_role        where role_name like concat('%', #{roleName},'%')        and note like concat('%',#{note},'%')    </select>

When we need to search for a database based on multiple parameters and the search results may return multiple records, we use the above configuration.

ParamterType = "map", input a map object as a parameter of the select statement. The key of each element in the map corresponds to # {roleName}, # {note} in the while clause}

Because the while clause only queries based on two parameters,Therefore, the map length is 2.. The value of map is the value of the query condition.

Map <String, String> paramsMap = new HashMap <> (); paramsMap. put ("roleName", "me"); // value is the condition value to be satisfied while note = "me" paramsMap. put ("note", "no"); // The Key is consistent with the # {note }#{ roleName} List in the SQL statement <Role> result = roleMapper. findRoleByMap (paramsMap );

Select id, role_name, note from t_role where role_name like concat ('% ',?, '%') And note like concat ('% ',?, '% ')

For example: select id, role_name, note from t_role where role_name like concat ("me") and note like concat ("no ")

 

ResultMap indicates the format of the returned "result": resultMap = roleMap. The definition of resultMap is as follows: (it can be understood that the key of resultMap is the attribute name or field name, and the value is the corresponding result value)

<ResultMap type = "chapter2.pojo. Role" id = "roleMap"> <id property = "id" column = "id"/> <! -- Primary key --> <result property = "roleName" column = "role_name"/> <! -- Ing relationship of common columns --> <result property = "note" column = "note"/> </resultMap>

<Id property = "id" column = "id" indicatesId is the primary key of the t_role table.The column name of the primary key is "id"

<Result property = "roleName" colum = "role_name"/> indicates that roleName is the attribute name of the POJO class, and "role_name" is the name of the t_role column in the database table.

 

Or use the "easy to understand" ing method: ---- parameter Annotation

The method defined in the RoleMapper interface:

    public List<Role> findRoleByAnnotation(@Param("roleName")String roleName, @Param("note")String note);

 

The SQL statement defined in the RoleMapper. xml configuration file: There is no paramterType to define the query parameters.

        <select id="findRoleByAnnotation"resultMap="roleMap">        select id,role_name,note from t_role        where role_name like concat('%', #{roleName},'%')        and note like concat('%',#{note},'%')    </select>

 

Client call method: Here, You can encapsulate multiple parameters to be queried without HashMap.

List<Role> res = roleMapper.findRoleByAnnotation("me", "no");for (Role role2 : res) {    System.out.println(role2);    }

 

Related Article

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.