Mybatis-Getting started


Installation

1、including the jar file in the classpath.

2、adding the dependency to your pom.xml.

Building SqlSessionFactory from XML

Every MyBatis application centers around an instance of SqlSessionFactory. A SqlSessionFactory instance can be acquired by using the SqlSessionFactoryBuilder. SqlSessionFactoryBuilder can build a SqlSessionFactory instance from an XML configuration file, or from a custom prepared instance of the Configuration class.

Building SqlSessionFactory without XML

MyBatis provides a complete Configuration class that provides all of the same configuration options as the XML file.

Acquiring a SqlSession from SqlSessionFactory

The SqlSession contains absolutely every method needed to execute SQL commands against the database.

Exploring Mapped SQL Statements

At this point you may be wondering what exactly is being executed by the SqlSession or Mapper class. The topic of Mapped SQL Statements is a big one, and that topic will likely dominate the majority of this documentation.

Scope and Lifecycle

It's very important to understand the various scopes and lifecycles classes we've discussed so far. Using them incorrectly can cause severe concurrency problems.

SqlSessionFactoryBuilder

This class can be instantiated, used and thrown away. There is no need to keep it around once you've created your SqlSessionFactory. Therefore the best scope for instances of SqlSessionFactoryBuilder is method scope.

SqlSessionFactory

Once created, the SqlSessionFactory should exist for the duration of your application execution. Therefore the best scope of SqlSessionFactory is application scope.

SqlSession

Each thread should have its own instance of SqlSession. Instances of SqlSession are not to be shared and are not thread safe. Therefore the best scope is request or method scope.

Mapper Instances

Mappers are interfaces that you create to bind to your mapped statements. the best scope for mapper instances is method scope.

相关