MyBatis Quick Start manual (updated occasionally upon study) and mybatis occasionally

Source: Internet
Author: User

MyBatis Quick Start manual (updated occasionally upon study) and mybatis occasionally

--- Restore content start ---

Preface:

  This article summarizes my learning content, and records some problems encountered during the learning process and precautions. Some content in the mybatis development manual will be referenced during compilation. Hope to help some friends who are learning. Some component versions used in this article are as follows: mybatis-3.4.2, junit-4.12, mysql-connector-5.0.7.

Ps: Let's talk about the development manual. I am not very clear about it in some places. The Chinese version also has the taste of machine turning... If you think the writing is good, just like it. If you think the writing is not good, give suggestions! _ (: Blank "blank )_

 

Directory :

 1. Quick Start

 Ii. xml configuration file

 Iii. xml ing File

 

Body: 1. Quick Start  1. Import the jar package of mybatis

To use MyBatis, place the mybatis-x.x.x.jar file in classpath. If you use Maven to build a project, place the following dependency code in the pom. xml file:

1 <dependency>2   <groupId>org.mybatis</groupId>3   <artifactId>mybatis</artifactId>4   <version>x.x.x</version>5 </dependency
Pom. xml 2. Build sessionFactory from the xml configuration file

In simple terms, there are two steps: ① get the input stream from the configuration file. ② Use the sqlSessionFactoryBuilder. build () method to pass in the input stream and obtain sqlSessionFactory.

String resource = "org/mybatis/example/mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

Configuration file:

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4   "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6   <environments default="development"> 7     <environment id="development"> 8       <transactionManager type="JDBC"/> 9       <dataSource type="POOLED">10         <property name="driver" value="${driver}"/>11         <property name="url" value="${url}"/>12         <property name="username" value="${username}"/>13         <property name="password" value="${password}"/>14       </dataSource>15     </environment>16   </environments>17   <mappers>18     <mapper resource="org/mybatis/example/BlogMapper.xml"/>19   </mappers>20 </configuration>
Configuration File 3. Obtain the session from sessionFactory
1 SqlSession session = sqlSessionFactory.openSession();
4. Run the ing SQL statement

Ing file and configuring SQL statements

1 <?xml version="1.0" encoding="UTF-8" ?>2 <!DOCTYPE mapper3   PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"4   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">5 <mapper namespace="org.mybatis.example.BlogMapper">6   <select id="selectBlog" resultType="Blog">7     select * from Blog where id = #{id}8   </select>9 </mapper>

Execute: use the "namespace. id (statement)" method for calling.

1 Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
5. Scope and lifecycle

SqlSessionFactoryBuilder: Generally, instances are not maintained for a long time. After sessionFactory is built, the instances can be destroyed.

SqlSessionFactory: Once created, it should always exist during the running period and there is no reason to clear or recreate it. We recommend that you use the singleton mode.

SqlSession: Because the thread is unsafe, there is a thread security problem. It is not recommended to exist in a static way. We recommend that you call the close () method to destroy the method after the method or request ends.

Ii. xml configuration file 1. enviroments and environment
1 <! -- Environments: Environment set. It can contain multiple environments. 2 default: the default environment of the environment set. You can customize it. 3. General -- developement: development mode, work: working Mode --> 4 <environments default = "development"> 5 <! -- Environment: environment, id: Specifies the mode of the environment, which can be customized --> 6 <environment id = "development">

  Mappings between default and id:The Development Manual does not provide enough information, but when I am learning in the video, I just say that the id and default must be consistent, and I have not said much about the details. In my test, default indicates the default environment attribute. At least one environment of this type is required in the environment set. That is to say, when constructing sessionFactory, if the specified environment parameter is not set, it will search for an environment based on the default parameter. Therefore, an environment with the same name must exist. If multiple environments exist in the environment set, if you do not want to use the default environment when building sessionFactory, you should specify the environment parameter.

2. transactionManager
1 <! -- TransactionManager: Specifies the transaction management mode. type: Specifies the transaction management mode, which is divided into JDBC and MANAGED2 JDBC. This configuration directly uses the JDBC commit and rollback settings, it depends on the connection obtained from the data source to manage the transaction scope. 3 MANAGED-transactions are not MANAGED by containers, such as spring and j2ee server context. The connection is closed by default. 4. However, some containers do not want this. Therefore, you need to set the closeConnection attribute to false to prevent its default close behavior. --> 5 <transactionManager type = "MANAGED"> 6 <property name = "closeConnection" value = "false"/> 7 </transactionManager>
3. dataSource
1 <! -- DataSource: Data Source. Configure the database connection information. 2 type: Connection type. There are three types: [UNPOOLED | POOLED | JNDI] --> 3 <dataSource type = "POOLED"> 4 <! -- Driver and url are used here, while driverClass and jdbcUrl are used in some configuration files, do not write an error --> 5 <property name = "driver" value = "$ {driverClass}"/> 6 <property name = "url" value = "$ {jdbcUrl }"/> 7 <property name = "username" value = "$ {username}"/> 8 <property name = "password" value = "$ {password}"/> 9 </ dataSource>

 

POOLED: "pool" type connection reduces the initialization and authentication time required to create a new connection instance. Is a popular processing method that allows concurrent Web applications to quickly respond to requests.

UNPOOLED: Enable and disable connections as requested. Frequent enabling and disabling may result in low performance efficiency and can be used if the performance requirement is not high.

JNDI: the implementation of this data source is to be used in containers such as ejbs or application servers. containers can configure data sources centrally or externally and place a reference to the JNDI context.

4. mappers and mapper
1 <! -- Mappers: mapper set. All mapper labels are under this tag --> 2 <mappers> 3 <! -- Mapper: registers the ing file or ing class, that is, to tell mybatis where to find the ing. There are four registration methods: --> 4 <! -- 1. Use the Path Structure in the project to specify the ing file --> 5 <mapper resource = "cn/edu/mybatis/test1/lelemapper. xml"/> 6 <! -- 2. Use the full class name to specify the ing class --> 7 <mapper class = "cn.edu. mybatis. test1.PeopleMapper"/> 8 <! -- 3. the scan base package of the specified mybatis will automatically contain all the ing files and ing files under the package (this method will be detailed when typeAliases is used) --> 9 <package name = "cn.edu. mybatis. test1 "/> 10 <! -- 4. the Uniform Resource Locator is used to specify the ing file (this method is hard to understand and cannot be tested after several tests, so the official example is used, hope you can tell me how to use it !) --> 11 <mapper url = "file: // var/mappers/BlogMapper. xml"/> 12 </mappers>
5. properties
1 <! -- Define a properties to reference external proerties. You can also use <property> under the tag to construct a properties 2 resource: reference file path --> 3 <properties resource = "db. properties "> 4 <! -- Note: when the property name is the same as that of the external file, the result is the value of the external file, no overwrite is generated --> 5 <property name = "password" value = "124567"/> 6 </properties>

After declaring properties, you can use the "$ {key}" method to obtain the corresponding value to improve the simplicity and versatility of the configuration. Example:

1  <dataSource type="POOLED">    2    <property name="driver" value="${driverClass}" />3    <property name="url" value="${jdbcUrl}" />4    <property name="username" value="${username}" />5    <property name="password" value="${password}" />6  </dataSource>
6. typeAliases
1 <typeAliases> 2 <! -- An alias for a full-class reputation. using an alias in the future is equivalent to using a full-class name. Note: even if an alias is declared, the full-class name can also be used, that is, the two can be mixed, however, it is generally not recommended to mix --> 4 <typeAlias type = "cn.edu. mybatis. test1.People "alias =" _ People "/> 5 <! -- Set a default alias for all classes in a package --> 6 <package name = "cn.edu. mybatis. test1"/> 7 </typeAliases>

  About typeAlias:You can use the @ Alias annotation to declare aliases for a class to reduce the use of configuration files. For example:

1 @Alias("people")2 public class People {...}

  About package and @ Alias:In the case of @ Alias annotation, the Alias declared in the annotation takes precedence. The default alias written in the development manual is the lower-case class name with the first letter. However, after testing, the default alias is the case-insensitive form of the class name, such as cn.edu. mybatis. the default alias for test1.People can be: people, People, and pEopLe. However, we recommend that you use lower-case class names.

  Note: In the following introduction, aliases are not used for the moment. Instead, full-class names are used to ensure rigor.

7. Others

Others, such as sestfactory and objectFactory, are not described here due to long space and not frequently used issues, if you are interested, you can learn about it on your own.

Iii. xml ing file 1. Basic CRUD labels

  Basic query:

1 <! -- Select: query statement. The specific SQL statement is written in the label. 2 parameterType: input parameter type. 3 resultType: output parameter type. 4 # {variable name}: It indicates a placeholder. It replaces the input parameter, only one input parameter can use the variable name as the placeholder --> 5 <select id = "findPeople" parameterType = "int" resultType = "cn.edu. mybatis. test1.People "> 6 select * from people where id = # {id} 7 </select>

  Add, delete, and modify:You can change the label to the corresponding insert, delete, and update parameters. The input and output parameters are the same as the query parameters. The SQL statements are also customized.

When the input parameter is a class, the statement is written as follows:

1   <update id="insert" parameterType="cn.edu.mybatis.test1.People">2       insert into people(name,age) values(#{name},#{age})3   </update>

In this case, the placeholder will correspond to the attributes of the class one by one. Therefore, a placeholder with the same name as the attribute must be used.

  Note:You can use $ {xxx} to insert a dynamic string in an SQL statement to implement dynamic SQL. However, this method causes SQL Injection risks and is not recommended. Mybatis provides better dynamic SQL methods, which will be introduced later.

2. Three Ways to call SQL statements
1 public void select () {2/* Call Method 1: */3 People people = session. selectOne ("cn.edu. mybatis. test1.lelemapper. findPeople ", 1); 4 System. out. println (people); 5/* Call Method 2: */6 lelemapper mapper = session. getMapper (lelemapper. class); 7 people = mapper. findPeople (1); 8 System. out. println (people); 9/* Call method 3: */10 people = mapper. findPeopleById (1); 11 System. out. println (people); 12}

The first method is to call the session method by passing in the "namespace. Statement id" and parameters for calling. The same applies to addition, deletion, and modification.

The second method declares an interface. The interface declares a method with the same id as a tag in the ing file and the same passed-out parameters. Then, you can use the session. getMapper () method to obtain the implementation of the interface, and then use the interface to call the method. This method is closer to the object-oriented operation method. At the same time, the interface is used for a certain degree of isolation, which eliminates some hidden dangers caused by long string writing. Is a recommended call method.

1 public interface PeopleMapper {2     People findPeople(int id);3 }

The third method seems to be slightly different from the second one. It belongs to a small variant. It uses the annotation configuration method to directly write SQL statements in the annotation, reducing the appearance of configuration files. We recommend that you use this method when writing some SQL statements with simple functional logic, which can greatly reduce the burden on the configuration file. Similarly, there are @ Insert, @ Update, and @ Delete.

1     @Select("select * from people where id = #{id}")2     People findPeopleById(int id);

  Note: If you only use annotations, you must register the ing Class in the er of the configuration file. If you have registered a ing file of the same name before, you do not need to register it.

3. the query returns multiple results and resolves conflicts between field names and attribute names.

When multiple results are returned, you only need to declare the type in the result set. mybatis is automatically encapsulated.

1   <select id="findAllPeople" resultType="cn.edu.test.People" >2       select * from people3   </select>
4. Resolving Conflicts between field names and attribute names -- resultMap

When the database field and object attribute names are different, the attribute cannot be obtained. For example, if the data type is the same but the table is PEOPLE (p_id, p_name, p_age), then the query statement previously used will return null, this is caused by the reflection mechanism. There are two solutions: First, you can use as in an SQL statement to rename the query result to be the same as the attribute name. This method is cumbersome and cumbersome. Second, mybatis provides a better solution, resultMap.

1 <resultMap type = "cn.edu. mybatis. test1.People" id = "lelemap"> 2 <! -- Column: database Field Name property: corresponding property name --> 3 <id column = "p_id" property = "id"/> 4 <result column = "p_name" property = "name"/> 5 <result column = "p_age" property = "age"/> 6 </resultMap>

In the query statement, change resultType to resultMap:

1   <select id="findAllPeople" resultMap="peopleMap" >2       select * from people3   </select>

This method can solve the conflict problem. Some more complex mappings will not be described in detail. You can query them by yourself. By the way,Generally, database columns are named in upper case, and words are separated by underscores (_). java attributes generally follow the hump naming method. In the setting tag of the configuration file, there isSet the mapUnderscoreToCamelCase attribute to true to enable automatic ing and conversion between the two naming methods.

5. To be continued

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.