Mybatis_reveiw-Mybatis official simple Demo

Source: Internet
Author: User

Mybatis_reveiw-Mybatis official simple Demo

When I went to school, a teacher told a story about this story. There are many ways to cut the apple. The first method is to use a nail clippers. The second method is to use machine tools, the third method is to use the hand-shaking tool for pinning fruit. Of course, we can all fulfill this simple requirement, but the apples cut out with a nail clipper must be pitfall, not beautiful enough, and may make people feel a little unappetizing. What about machine tools? It may cause a lot of waste. Originally, an elegant Apple became a square with only a few bits. Third, because it was designed specifically for apple peel cutting, it is theoretically the most suitable solution to the problem of apple peel cutting.

 

A good architecture is actually very simple to do. Apart from in-depth understanding of the principles and components of some architectures, we also need to select an appropriate technology to solve specific problems. Many of us say that hibernate is not as good as ibatis, or that struts1 is not as good as struts2.x on the cloud. It may also be because of personal preferences to judge arbitrary problems, any technology has its own meaning and advantages. I used to like the hybrid itpub forum very much. I have always remembered a sentence in the personalized signature of an Oracle expert. The general idea is that every Oracle function has a specific solution to the problem and there is no better technology, only more suitable technologies are available.

 

 

Relatively speaking, the Mybatis documentation is quite good, because some caring people translate official documents into Chinese, which makes it much easier for programmers who look at Chinese documents.

 

Enter the Demo of Mybatis for the first entry.

 

 

Step 1: Create an Eclipse project and create a ing table on Mysql

 

Here, we can use Eclipse to create a simplest Java Project. MyBatis also implements the VO ing from VO to database tables, so we prepare class files and database tables. The class is defined as follows:

public class Tiger {    private String name;    private double weight;    private int age;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public double getWeight() {        return weight;    }    public void setWeight(double weight) {        this.weight = weight;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + age;        result = prime * result + ((name == null) ? 0 : name.hashCode());        long temp;        temp = Double.doubleToLongBits(weight);        result = prime * result + (int) (temp ^ (temp >>> 32));        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Tiger other = (Tiger) obj;        if (age != other.age)            return false;        if (name == null) {            if (other.name != null)                return false;        } else if (!name.equals(other.name))            return false;        if (Double.doubleToLongBits(weight) != Double                .doubleToLongBits(other.weight))            return false;        return true;    }    @Override    public String toString() {        return Tiger [name= + name + , weight= + weight + , age= + age                + ];    }}

The database table is defined as follows:

create table tiger1(id int(5),    name varchar(30),   age int(4),    weight double)
Step 2: Find the jar package of Mybatis from the Internet

From Baidu on the Internet, we can find the download location of the jar package of Mybatis. We 'd better put the jar package of the source code of Mybatis and the jar package dependent on it into our DEMO space, convenience for later learning.

Click our JavaProject, select properties, and find buildPath to introduce the jar package under Mybatis to the current project.

The following is a list of jar packages I have introduced:

Asm-3.3.1.jar

Cglib-2.2.2.jar

Commons-logging-1.1.1.jar

Javassist-3.17.1-GA.jar

Log4j-1.2.17.jar

Log4j-api-2.0-rc1.jar

Log4j-core-2.0-rc1.jar

Mybatis-3.2.6.jar

Mysql-connector-java-3.1.6-bin.jar

Slf4j-api-1.7.5.jar

Slf4j-log4j12-1.7.5.jar

Step 3: Create a configuration file Mybatis-config.xml file for Mybatis

A file is created under the src folder named MyBatis-config.xml with the following content:

 
 

The following is a brief introduction to the Elements in this file:

The content of the MyBatis file is very complex. Here are just a few necessary files, the first line above, that is? The xml line is required by the XML file. We can see the content of this line in the xml file. The content in the second row is used to parse the dtd file of the current XML. The dtd file specifies the content of the current file, which restricts the XML. According to the XML specification, the current XML only has one root element. The root element is named configuration. This basic XML contains three subnodes, the first subnode is setting, and the second subnode is environments. The third subnode is mapper. Of course, it can have more configurations, but based on the current document, we will look at the role of these three nodes in turn.

The first node is setting. As the name suggests, this is the configuration item of mybatis. The flexibility of a software depends on the items that can be configured. At this point, mybatis provides a large number of configuration items. logImpl = LOG4J here, we use this configuration command MyBatis to use Log4j to implement the log function.

The second node is environments. In this project, you can configure multiple environments. In this node, we configure database-related information. The default environment is development, in this node, transactionManager is used to configure transaction attributes. The importance of transactions in database processing is unquestionable. How to configure transactions is also a very important thing in the framework design. It can be said that all settings that affect the accuracy of business data are very serious and must be fully valued. The following dataSource is a required option to configure dataSource. To use a dataSource, we must provide necessary information, this information is mainly used to describe which database to connect to and what information is used to connect to the database: the URL address, port number, driver, user name, and password of the database, in this DEMO, the above configuration uses the POOLED data source, so the configuration items must have some configuration items about the database connection pool, here we use the default.

The third node is mapper, which is a very important file. Its main function is to establish the ing between objects and database tables. More specifically, by configuring SQL statements in Mapper, you can establish the ing between the SQL statement query result set and the Object to hide the implementation between the Object and the database table in the java file. In fact, this is similar to what Hibernate does. It is just the difference between the machine tool and the skin-cutting machine mentioned in the preface.

Step 4: Create a tiing configuration file tiger. xml for database tables and SQL statements.

Create a file named tiger. xml under the src folder. This file mainly establishes the ing between database tables and objects. The statements in this file are as follows;

 
   
      select * from Tiger where id = #{id}  
 

The first line of the description of this simple file is still our favorite XML descriptor. It is easy to find this line in all XML files. The second line, is the dtd file of the current file. The following describes how to find the corresponding object through the database table. # {Id} indicates that the select statement lacks a parameter named id. After this parameter is added, You can execute this SQL statement to obtain the corresponding java object.

Step 5: Obtain the SqlSessionFactory object

Based on the descriptions of several important object declaration cycles in the official documents, we use the simple Singleton mode to create SqlSessionFactory objects. The related code is as follows. Create a file named MybatisUtil under the Src folder. The content of this file is as follows:

import java.io.IOException;import java.io.InputStream;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;public class MybatisUtil {        private static SqlSessionFactory sqlSessionFactory;    public static SqlSessionFactory getSessionFactory() throws IOException {        if(sqlSessionFactory==null){            String resource = mybatis-config.xml;            InputStream inputStream = Resources.getResourceAsStream(resource);            return new SqlSessionFactoryBuilder().build(inputStream);        }else{            return sqlSessionFactory;        }    }}

This tool class is used to instantiate an object during the first request of SqlSessionFactory. if the object is requested later, the instance of the object is directly returned. Among them, the above Resources object is a public class provided by Mybatis for finding xml files. We can directly call it in the above Order when using it.

But here we need to understand several concepts. These concepts are Resources, SqlSessionFactoryBuilder, SqlSessionFactory, SqlSession, and er. For these five objects, we will explain them one by one:

Resources is a tool class provided by Mybatis for finding resource files. It is actually a useful tool class, which is everywhere in the framework, it is an effective measure to prevent repetition. In fact, it is relatively simple to do things. We can write one by ourselves, but can someone else provide it? So you just need to remember that this class can be used. Why should I use a pair of pliers?

SqlSessionFactoryBuilder is a class used to create the SqlSessionFactory object. This object is used to create SqlSessionFactory. It creates a SqlSessionFactory by using the resource files we provide or other defined objects, we can think of this builder as a one-time engineering contractor. After you create a SqlSession factory for me, You can disband it. Therefore, the life cycle of this method is, the best thing is at the method level. After the method is over, the contractor can disband it. Otherwise, we will provide the employer with resources to survive, eat, drink, and pull, this is not an option, because they are not working in the future, and we are still raising idle people. This is too difficult. What if I need to do it again? First, we generally cannot meet this requirement. Second, we only need to re-organize the contractor for reconstruction.

The SqlSessionFactory object is mainly used to generate a factory for SqlSession. This is the factory for continuously obtaining SqlSession. The best practice is to keep only one SessionFactory for the entire project. It is similar to the nuclear power plant we are on the Red Guard. With this, we can continuously obtain SqlSession, but we only need one, that is, the method in the above Code. The above is the implementation of the singleton mode. If you do not understand it, you can take a good look at the static + acquisition method. The key point is that this object is only instance once, rather than the second instance.

The last is SqlSession, the most important object. session means session, which is a conversation process. We can remember the life cycle of this method from this perspective, that is, a session. From the suggestions in the official Mybatis documentation, we can see that if there is no DI framework, we should limit the lifecycle of the SqlSession object to one session when calling Mybatis ourselves. The lifecycle of the sqlSession object. It is born in the SqlSessionFactory. openSession () method and ends with the SqlSession. close () method. To ensure that this sqlSession is disabled, write it in the finally block.

Step 6: Compile the main method to complete your first Mybatis Demo.

After all the above files are written, we can write a main method to make the above Code work. In Src, we can write a class and then write a main method in it, the method is as follows:

 public static void main(String[] args) throws IOException {        SqlSessionFactory sessionFactory = MybatisUtil.getSessionFactory();        SqlSession session = sessionFactory.openSession();        try {            Tiger tiger = session.selectOne(selectTiger,1);            System.out.println(tiger.getAge());        } finally{            session.close();        }    }

To see the entire execution process, we can configure a simple log4j. properties to make the Log4j configuration take effect, and put the log4j. properties containing the following content under the src Folder:

log4j.rootLogger=debug, stdoutcom.samsung.mybatis.Tiger=TRACElog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

Click execute. If the previous step is correct, the background will output the following content:

DEBUG [main]-Logging initialized using 'class org. apache. ibatis. logging. slf4j. Slf4jImpl 'adapter.

DEBUG [main]-Logging initialized using 'class org. apache. ibatis. logging. log4j. Log4jImpl 'adapter.

DEBUG [main]-PooledDataSource forcefully closed/removed all connections.

DEBUG [main]-PooledDataSource forcefully closed/removed all connections.

DEBUG [main]-PooledDataSource forcefully closed/removed all connections.

DEBUG [main]-PooledDataSource forcefully closed/removed all connections.

DEBUG [main]-Opening JDBC Connection

DEBUG [main]-Created connection 14962806.

DEBUG [main]-Setting autocommit to false on JDBC Connection [com. mysql. jdbc. Connection @ e000076]

DEBUG [main]-==> Preparing: select * from Tigerwhere id =?

DEBUG [main]-==> Parameters: 1 (Integer)

DEBUG [main]-<= Total: 1

100

DEBUG [main]-Resettingautocommit to true on JDBC Connection [com. mysql. jdbc. Connection @ e000076]

DEBUG [main]-Closing JDBC Connection [com. mysql. jdbc. Connection @ e000076]

DEBUG [main]-Returned connection 14962806 to pool.

Let's look at the preceding execution process. First, create an object-class adapter for logs, establish a connection pool, open a JDBC connection, set the autoCommit attribute of the current connection, execute preparedstatement, and return the query result, parse the resultset, set autocommit to true, close the current connection, and return the current connection to the connection pool.

In addition, you can use annotations to obtain SqlSessionFactory and execute SQL:

In addition, Mybatis also supports annotation to avoid xml files. annotation has two advantages. The first advantage is that the automatic prompt function of IDE can be used, this function is very useful for our IDE-dependent developers. The second is to reduce errors, Because XML is a file based on strings after all, it is troublesome to troubleshoot string errors.

The method for modifying the above project to annotation is as follows.

Add a TigerMapper. java interface file as follows:

import org.apache.ibatis.annotations.Select;public interface TigerMapper {    @Select(select * from Tiger where id = #{id})    public Tiger selectTiger(int id);}

Modify the MybatisUtil. java file as follows:

import java.io.IOException;import org.apache.ibatis.datasource.pooled.PooledDataSource;import org.apache.ibatis.mapping.Environment;import org.apache.ibatis.session.Configuration;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.apache.ibatis.transaction.TransactionFactory;import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;public class MybatisUtil {        private static SqlSessionFactory sqlSessionFactory;    public static SqlSessionFactory getSessionFactory() throws IOException {        if(sqlSessionFactory==null){            PooledDataSource dataSource = new PooledDataSource();            dataSource.setDriver(com.mysql.jdbc.Driver);            dataSource.setUrl(jdbc:mysql://127.0.0.1:3306/test);            dataSource.setUsername(chenzw);            dataSource.setPassword(7758521);            TransactionFactory transactionFactory = new JdbcTransactionFactory();            Environment environment = new Environment(development, transactionFactory, dataSource);            Configuration configuration = new Configuration(environment);            configuration.addMapper(TigerMapper.class);            return new SqlSessionFactoryBuilder().build(configuration);        }else{            return sqlSessionFactory;        }    }}

Modify the main method as follows:

  public static void main(String[] args) throws IOException {        SqlSessionFactory sessionFactory = MybatisUtil.getSessionFactory();        SqlSession session = sessionFactory.openSession();        try {            Tiger tiger = session.getMapper(TigerMapper.class).selectTiger(1);            System.out.println(tiger.getName());        } finally{            session.close();        }    }

The execution result is as follows:

DEBUG [main]-Logginginitialized using 'class org. apache. ibatis. logging. slf4j. Slf4jImpl 'adapter.

DEBUG [main]-PooledDataSourceforcefully closed/removed all connections.

DEBUG [main]-PooledDataSourceforcefully closed/removed all connections.

DEBUG [main]-PooledDataSourceforcefully closed/removed all connections.

DEBUG [main]-PooledDataSourceforcefully closed/removed all connections.

DEBUG [main]-Opening JDBCConnection

DEBUG [main]-Createdconnection 32960703.

DEBUG [main]-Settingautocommit to false on JDBC Connection [com. mysql. jdbc. Connection @ 1f6f0bf]

DEBUG [main]-==> Preparing: select * from Tiger where id =?

DEBUG [main]-==> Parameters: 1 (Integer)

DEBUG [main]-<= Total: 1

Ziwen

DEBUG [main]-Resettingautocommit to true on JDBC Connection [com. mysql. jdbc. Connection @ 1f6f0bf]

DEBUG [main]-Closing JDBCConnection [com. mysql. jdbc. Connection @ 1f6f0bf]

DEBUG [main]-Returnedconnection 32960703 to pool.

 

This is the simplest Demo officially provided. In the future, we will explore other official features step by step based on this Demo to deepen our understanding of Mybatis.






 





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.