Java Persistence with MyBatis summary 2

Source: Internet
Author: User
Tags class definition apache tomcat

The most critical component of MyBatis is sqlsessionfactory, from which we can get sqlsession and execute the mapped SQL statement. Sqlsessionfactory objects can be created through XML-based configuration information or Java APIs.

1 mybatis environment, environments configuring the default database environment

MyBatis supports configuring multiple DataSource environments, enabling applications to be deployed to different environments, such as dev (development environment), test (testing for Change), QA (Quality assessment Environment), UAT (User acceptance environment), PRODUCTION (production environment), which can be set by default The environment value is set to the desired environment ID value.

2 per Environment environment configuration, DataSource and TransactionManager required

The DataSource element is used to configure database connection properties. Typical configurations are as follows

<datasource type="Pooled"><property name="Driver"Value="${jdbc.driverclassname}"/><property name="URL"Value="${jdbc.url}"/><property name="username"Value="${jdbc.username}"/><property name="Password"Value="${jdbc.password}"/></datasource>

The type of 2.1 DataSource can be configured as one of its built-in types, such as Unpooled,pooled,jndi.
? Setting the type to Unpooled,mybatis creates a new connection for each database operation and closes it. The way
For simple applications with only a small number of concurrent users.
? If you set the property to Pooled,mybatis, a database connection pool is created, and a connection in the connection pool is used as the data
Library operations. Once the database operation is complete, MyBatis will return this connection to the connection pool. In a development or test environment, you often use this
ways.
? If the type is set to Jndi,mybatis from the application server to the configured JNDI data source DataSource get the database
Connection. In a production environment, this approach is preferred.

2.2 Transaction manager TransactionManager

MyBatis supports two types of transaction managers: JDBC and MANAGED.

    • The JDBC transaction manager is used as a time when the application is responsible for managing the life cycle of database connections (commit, fallback, and so on). When you set the TransactionManager property to Jdbc,mybatis, the Jdbctransactionfactory class is used to create the TransactionManager. For example, an application deployed to Apache Tomcat requires the application to manage its own transactions.
    • The MANAGED transaction manager is used when the application server is responsible for managing the database connection life cycle. When you set the TransactionManager property to MANAGED, MyBatis internally uses the Managedtransactionfactory class to create the transaction manager TransactionManager. For example, when a Java EE application is deployed on a similar Jboss,weblogic,glassfish application server, they use EJBS to manage the transaction management capabilities of the application server. In these administrative environments, you can use the MANAGED transaction manager.

Managed is the meaning of hosting, that is, the application itself does not manage the transaction, but the transaction management to the application on the server to manage.

3 Type alias typealiases,

In the configuration file, for the Resulttype and ParameterType property values, we need to use the fully qualified name of the JavaBean.

Instead of using fully qualified names everywhere, we can take an alias for the fully qualified name, and then it needs to use the fully qualified name where the alias is used.

<typealiases><typealias alias="Student " type= " Com.mybatis3.domain.Student" /><typealias alias="Tutor" type="  com.mybatis3.domain.Tutor" /><package name="Com.mybatis3.domain  " /></typealiases>

Another way to alias JavaBeans, use annotation @alias:

@Alias ("studentalias")publicclass  student{}

Note: @Alias annotations will overwrite the <typeAliases> definitions in the configuration file.

4 Type Processor Typehandlers

How does MyBatis know to use the SetString () method with the Setint () and String type properties for an Integer type property?
In fact, MyBatis is determined by using the type handlers.

MyBatis uses built-in type processors for the following types: All basic data types, basic types of package types, byte[], java.util.Date, Java.sql.Date, Java,sql. Time, Java.sql.Timestamp, Java enumeration type, and so on. So when MyBatis discovers that the type of the attribute belongs to the above type, he uses the corresponding type processor to set the value to PreparedStatement, as well as a similar process when building JavaBean from the SQL result set.

For custom types, you need to create a custom type processor yourself.

MyBatis provides an abstract class basetypehandler<t> that we can inherit from this class to create a custom type processor.

For example, suppose the table STUDENTS has a PHONE field with a type of VARCHAR (15), and JavaBean Student has a phonenumber attribute of the PhoneNumber class definition type.

There is a property that is the following class, the PhoneNumber class

 Public classphonenumber{PrivateString CountryCode;PrivateString statecode;PrivateString number; PublicPhoneNumber () {} PublicPhoneNumber (String CountryCode, String statecode, Stringnumber) { This. CountryCode =CountryCode; This. Statecode =statecode; This. Number =Number ;} PublicPhoneNumber (Stringstring){if(string!=NULL) {string[] parts=string. Split ("-");if(Parts.length >0) This. CountryCode = parts[0];if(Parts.length >1) This. statecode = parts[1];if(Parts.length >2) This. Number = parts[2];}} PublicString getasstring () {returnCountryCode +"-"+ Statecode +"-"+Number ;}//Setters and getters}
View Code

and student is defined as follows

 Public class student{private  Integer ID; Private String name; Private String Email; Private PhoneNumber phone; // Setters and Getters}
View Code

4.1 The type processor created is as follows

Importjava.sql.callablestatement;importjava.sql.preparedstatement;importjava.sql.resultset; Importjava.sql.sqlexception;importorg.apache.ibatis.type.basetypehandler;importorg.apache.ibatis.type.jdbctype ; importcom.mybatis3.domain.PhoneNumber; Public classPhonetypehandler extends Basetypehandler<phonenumber>{@Override Public voidSetnonnullparameter (PreparedStatement PS,inti,phonenumber parameter, Jdbctype jdbctype) throwssqlexception{ps.setstring (i, parameter.getasstring ());} @Override PublicPhoneNumber Getnullableresult (ResultSet rs, stringcolumnname) throws sqlexception{return NewPhoneNumber (rs.getstring (ColumnName));} @Override PublicPhoneNumber Getnullableresult (ResultSet RS,intcolumnindex) throws sqlexception{return NewPhoneNumber (rs.getstring (ColumnIndex));} @Override PublicPhoneNumber Getnullableresult (CallableStatement cs,intcolumnindex) throws sqlexception{return NewPhoneNumber (cs.getstring (ColumnIndex));}}

Description: We use the ps.setstring () and rs.getstring () methods because the phone column is a VARCHAR type.

4.2 Once we have implemented a custom type processor, we need to register it in 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="application.properties"/><typehandlers> <typehandler handler="Com.mybatis3.typehandlers.PhoneTypeHandler"/></typehandlers></configuration>

After registering Phonetypehandler, MyBatis is able to store the object value of the Phone type on a VARCHAR-type column.

5 SQL Mapping Definition Mappers

The SQL mapping statements contained in the Mapper XML file will be applied by using their statementid to execute. We need to configure the location of the SQL Mapper file in the Mybatis-config.xml file.

<mappers>    <mapper resource="com/mybatis3/mappers/studentmapper.xml" / >    <mapper url="file:///D:/mybatisdemo/app/mappers/TutorMapper.xml" />    Class="com.mybatis3.mappers.TutorMapper" />    <package Name="com.mybatis3.mappers" /></mappers>

The properties of each of these <mapper> tags help load the mapping mapper from different types of resources:
? The resource property is used to specify the mapper file in the classpath.
? The URL property is used to point to the mapper file through a full file system path or Web URL address
? The class attribute is used to point to a mapper interface
? The package attribute is used to point to the packet name where the Mapper interface can be found

Java Persistence with MyBatis summary 2

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.