The initial acquaintance MyBatis MyBatis

       

Initial MyBatis

 

What is MyBatis?

MyBatis is to support excellent persistence framework .MyBatis custom SQL, stored procedures and advanced mapping avoids almost all of the JDBC code and manual setting parameters and get the result set .MyBatis can configure and simple to use native Map XMl or comments, interface and Java POJO (plain Old java objects, ordinary Java objects) to database records in.
***

MyBatis how to install?

Download jar package

To use MyBatis, only mybatis-xxxjar file can be placed in the classpath, web projects into the jar package lib package under the WEB-INF
If Maven to build the project, you need to put the code following dependency pom.xml file:

    <dependency>
        <groupId>org.mybatis</groupId> <artifactId>mybatis</artifacId> <version>x.x.x</version> //版本号 </dependency>

MyBatis functional architecture

We Mybatis functional architecture consists of three layers

  1. API interface layer: API provides an interface to external use, by the developer to manipulate these local database API interface layer receiving a call request for calling the data processing will be done layer specific data processing.
  2. Data processing layer: responsible for specific SQL parsing find .SQL .SQL execution and implementation of the results of the mapping process, etc. Its main purpose is to complete the operation at the request of a database call.
  3. Base support layer: responsible for the most basic functions of support, including connection management, transaction management, load and configure caching, these are common things that will draw them out as the most basic components. Provide the most basic data processing for the upper layer supports
    ***

    MyBatis advantages and disadvantages

    advantage:
  • Easy to learn: small and simple in itself does not depend on any third party, as long as the easiest to install two jar files + configure several sql mapping file is easy to learn, easy to use, through documentation and source code, you can compare fully grasp it. design and implementation.
  • Flexible: mybatis does not impose any impact on the existing design of the application or the database. sql written in xml, to facilitate unified management and optimization. By sql basically realize we do not use data access framework can achieve all the features for more.
  • Sql release coupling program code: DAO layer by providing the data access logic and business logic separated from the system design more clearly, easier to maintain, easier unit testing. sql and the code, which enhances maintainability.
  • Providing a mapping label, field support orm object relationship mapping database
  • Tags provide object-relational mapping, support for object-relational form maintenance
  • Providing xml tags, support the preparation of dynamic sql.

Disadvantages:

  • When writing SQL statements heavy workload, especially in the field more, the association table for a long time, especially
  • SQL statement depends on the database, resulting in poor portability database, the database can not be replaced.
  • Framework is quite simple, there are features missing, although simplifies data binding code, but the whole actual underlying database queries still have to write your own workload is relatively large, but not easy to adapt to rapid database modifications.
  • Poor secondary cache mechanism
    ***

    MyBatis use

    1. Create Mybatis core configuration file == 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"> <!--通过这个配置文件,完成mybatis与数据库的连接 --> <configuration> <!-- 注意此配置文件内的元素的 --> <!-- 引入database.properties文件 --> <properties resource="database.properties"/> <!-- 可以配置在Java 属性配置文件中 --> <!--配置mybatis的log实现为LOG4J --> <!-- 配置后,后台就会有sql语句的输出 --> <settings> <!-- 修改 MyBatis 在运行时的行为方式 --> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <!-- 为 Java 类型命名一个别名(简称) --> <package name="cn.smbms.pojo"/> </typeAliases> <environments default="development"> <!-- 环境 --> <environment id="development"> <!-- 环境变量 --> <!-- 配置事务管理 ,采用JDBC管理事务--> <transactionManager type="JDBC"/> <!-- 事务管理器 --> <!-- POOLED是mybatis的 数据源 --> <!-- JNDI是基于tomcat的数据源 --> <dataSource type="POOLED"> <!-- 数据源(UNPOOLED,POOLED,JNDI) --> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!-- pojo的映射文件UserMapper引入到配入到配置文件中 --> <mappers> <!-- 映射器 --> <!-- resource要写成路径 --> <mapper resource="cn/smbms/dao/UserMapper.xml"/> </mappers> </configuration>

The effect of several common elements mybatis-config.xml file is as follows:

1.configuration: root element node configuration file

2.properties: properties specified by attribute file from an external resource attribute
(database.properties), database.properties attribute file described configuration database connection, a database comprising a drive (jdbc.driver), connected to the database url (jdbc.url), database user name (jdbc.user), database password (jdbc.pwd), is also the location / directory under resoureces.

3.settings: set some behavior MyBatis operation, such as setting here MyBatis log log implemented as LOG4J, realize that the use of log4j logging.

4.environments: shows an arrangement of multiple sets MyBatis operating environment, the SQL mapped to a plurality of different databases, this element node may be configured environment a plurality of child element node, but must specify a default execution environment (specified by default) .

5.environment: MyBatis configuration of a set of runtime environment, the need to specify the ID, transaction management, data source configuration and other information on the operating environment.

6.mappers: role is to tell MyBatis where to find SQL mapping file (the file contents are developer-defined mapping sql statement), the entire project can have one or more SQL mapping files

7.mapper: mappers child element node, specify SQL mapping file path, wherein the expression value of the resource attribute sql
path (path-based resource) mapped file
== == Note: element nodes mybatis-config.xml file there is a certain order, node locations, if not ranked in order, then the XML file will complain

2. Next, prepare persistent classes and SQL mapping files
we first define a simple class (user category) user class attributes is a table in our database fields (user table)

public class User {
    private Integer id; //id private String userCode; //用户编码 private String userName; //用户名称 private String userPassword; //用户密码 private Integer gender; //性别 private Date birthday; //出生日期 private String phone; //电话 private String address; //地址 private Integer userRole; //用户角色 private Integer createdBy; //创建者 private Date creationDate; //创建时间 private Integer modifyBy; //更新者 private Date modifyDate; //更新时间 //省略getter,setter方法

== == Note: Under normal circumstances our class database and table names are the same

Next created SQL mapping file, complete the mapping and POJO (Entity class), the document is an XML file

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.smbms.dao.UserMapper"> <!--查询用户表记录数 --> <select id="count" resultType="int"> select count(1) as count from smbms_user </select> </mapper> 

== Experience ==: SQL mapping files are generally corresponds to the corresponding POJO (Entity class), it usually takes the name of POJO + rule Mapper to be named, such as the mapping file we created, called UserMapper.xml ( mapping file is placed under the package dao)

The meaning of each element of the configuration file:
Mapper: root element node mapping file, only one property namespace
namespace: used to distinguish different mapper, a globally unique
select: express query, is one of MyBatis common elements, common properties as follows :
ID attribute: the unique identifier for the namespace
resultType properties: indicates the type of the return value of the SQL statement, SQL statements returned here is of type int

Next, create a test class, adding JUnit4 in the project, create a test class (UserMapperTest.java) test code is as follows:

public class UserMapperTest {
    public static void main(String[] args) throws Exception { //1.读取全局配置文件:mybatis-config.xml String resource="mybatis-config.xml"; //获取mybatis-config.xml文件的输入流 InputStream is= Resources.getResourceAsStream(resource); //2.创建SqlSessionFactory对象 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is); //创建SqlSession int count=0; SqlSession sqlSession=null; sqlSession=factory.openSession(); count=sqlSession.selectOne("com.smbms.dao.user.UserMapper.count"); //3.关闭SqlSession对象 sqlSession.close(); System.out.println(count); } }

Because every time we have to execute SQL statements to create these objects, so that there will be a lot of redundant code, we put these repetitive code into a tool to extract class, after the call of these tools directly to
creation tool class: MyBatisUtil

public class MyBatisUtil {
    private static SqlSessionFactory factory; static { try { InputStream is= Resources.getResourceAsStream("mybatis-config.xml"); factory=new SqlSessionFactoryBuilder().build(is); }catch (IOException e){ e.printStackTrace(); } } public static SqlSession createSqlSession(){ return factory.openSession(false); } public static void closeSqlSession(SqlSession sqlSession){ if (null!=sqlSession){ sqlSession.close(); } } }

Look at the back of the specific use SQLSession second way

MyBatis basic elements - the core object

==SqlSessionFactoryBuilder==

1.build () method uses the three forms of the configuration information, namely the InputStream (byte stream), Reader (character stream, the Configuration (type)
2.SqlSessionFactoryBuilder great feature is used that is lost

==SqlSessionFactory==

1.openSession () method to get SqlSession instance, openSession () parameter passing true to close the transaction control, automatic submit, false open transaction control mechanisms. The default is true.
2.SqlSessionFactory Once created, it will always present during the entire application is running.

==SqlSession==

1.SqlSession object persistence for performing operations, similar to the JDBC Connection.
2.SqlSession corresponds to a database session, SqlSession not thread safe.
3.SqlSession used in two ways

The first use:
1. Now add a file, select a node Mapper

<!--查询用户列表-->
<select id="getUserList" resultType="com.smbms.pojo.User"> SELECT * FROM USER </select>

2. Writing Test

SqlSession sqlSession=null;
List<User> userList=new ArrayList<User>(); 
try{
    sqlSession= MyBatisUtil.createSqlSession();
    userList=sqlSession.selectList("com.smbms.dao.user.UserMapper.getUserList"); 
}catch (Exception ex){ ex.printStackTrace(); }finally { MyBatisUtil.closeSqlSession(sqlSession); } for (User user : userList) { System.out.println(user.getUserName()); }

The second use:
Based on the above Mapper configuration file
1. Program Interface

public interface UserMapper {
    /** * 获取用户列表 * @return */ List<User> getUserList(); }

2. Writing Test

SqlSession sqlSession=null;
List<User> userList=new ArrayList<User>(); 
try{
    sqlSession= MyBatisUtil.createSqlSession();
    userList=sqlSession.getMapper(UserMapper.class).getUserList();
}catch (Exception ex){
    ex.printStackTrace();
}finally { MyBatisUtil.closeSqlSession(sqlSession); } for (User user : userList) { System.out.println(user.getUserName()); }

What is MyBatis?

MyBatis is to support excellent persistence framework .MyBatis custom SQL, stored procedures and advanced mapping avoids almost all of the JDBC code and manual setting parameters and get the result set .MyBatis can configure and simple to use native Map XMl or comments, interface and Java POJO (plain Old java objects, ordinary Java objects) to database records in.
***

MyBatis how to install?

Download jar package

To use MyBatis, only mybatis-xxxjar file can be placed in the classpath, web projects into the jar package lib package under the WEB-INF
If Maven to build the project, you need to put the code following dependency pom.xml file:

    <dependency>
        <groupId>org.mybatis</groupId> <artifactId>mybatis</artifacId> <version>x.x.x</version> //版本号 </dependency>

MyBatis functional architecture

We Mybatis functional architecture consists of three layers

  1. API interface layer: API provides an interface to external use, by the developer to manipulate these local database API interface layer receiving a call request for calling the data processing will be done layer specific data processing.
  2. Data processing layer: responsible for specific SQL parsing find .SQL .SQL execution and implementation of the results of the mapping process, etc. Its main purpose is to complete the operation at the request of a database call.
  3. Base support layer: responsible for the most basic functions of support, including connection management, transaction management, load and configure caching, these are common things that will draw them out as the most basic components. Provide the most basic data processing for the upper layer supports
    ***

    MyBatis advantages and disadvantages

    advantage:
  • Easy to learn: small and simple in itself does not depend on any third party, as long as the easiest to install two jar files + configure several sql mapping file is easy to learn, easy to use, through documentation and source code, you can compare fully grasp it. design and implementation.
  • Flexible: mybatis does not impose any impact on the existing design of the application or the database. sql written in xml, to facilitate unified management and optimization. By sql basically realize we do not use data access framework can achieve all the features for more.
  • Sql release coupling program code: DAO layer by providing the data access logic and business logic separated from the system design more clearly, easier to maintain, easier unit testing. sql and the code, which enhances maintainability.
  • Providing a mapping label, field support orm object relationship mapping database
  • Tags provide object-relational mapping, support for object-relational form maintenance
  • Providing xml tags, support the preparation of dynamic sql.

Disadvantages:

  • When writing SQL statements heavy workload, especially in the field more, the association table for a long time, especially
  • SQL statement depends on the database, resulting in poor portability database, the database can not be replaced.
  • Framework is quite simple, there are features missing, although simplifies data binding code, but the whole actual underlying database queries still have to write your own workload is relatively large, but not easy to adapt to rapid database modifications.
  • Poor secondary cache mechanism
    ***

    MyBatis use

    1. Create Mybatis core configuration file == 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"> <!--通过这个配置文件,完成mybatis与数据库的连接 --> <configuration> <!-- 注意此配置文件内的元素的 --> <!-- 引入database.properties文件 --> <properties resource="database.properties"/> <!-- 可以配置在Java 属性配置文件中 --> <!--配置mybatis的log实现为LOG4J --> <!-- 配置后,后台就会有sql语句的输出 --> <settings> <!-- 修改 MyBatis 在运行时的行为方式 --> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <!-- 为 Java 类型命名一个别名(简称) --> <package name="cn.smbms.pojo"/> </typeAliases> <environments default="development"> <!-- 环境 --> <environment id="development"> <!-- 环境变量 --> <!-- 配置事务管理 ,采用JDBC管理事务--> <transactionManager type="JDBC"/> <!-- 事务管理器 --> <!-- POOLED是mybatis的 数据源 --> <!-- JNDI是基于tomcat的数据源 --> <dataSource type="POOLED"> <!-- 数据源(UNPOOLED,POOLED,JNDI) --> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <!-- pojo的映射文件UserMapper引入到配入到配置文件中 --> <mappers> <!-- 映射器 --> <!-- resource要写成路径 --> <mapper resource="cn/smbms/dao/UserMapper.xml"/> </mappers> </configuration>

The effect of several common elements mybatis-config.xml file is as follows:

1.configuration: root element node configuration file

2.properties: properties specified by attribute file from an external resource attribute
(database.properties), database.properties attribute file described configuration database connection, a database comprising a drive (jdbc.driver), connected to the database url (jdbc.url), database user name (jdbc.user), database password (jdbc.pwd), is also the location / directory under resoureces.

3.settings: set some behavior MyBatis operation, such as setting here MyBatis log log implemented as LOG4J, realize that the use of log4j logging.

4.environments: shows an arrangement of multiple sets MyBatis operating environment, the SQL mapped to a plurality of different databases, this element node may be configured environment a plurality of child element node, but must specify a default execution environment (specified by default) .

5.environment: MyBatis configuration of a set of runtime environment, the need to specify the ID, transaction management, data source configuration and other information on the operating environment.

6.mappers: role is to tell MyBatis where to find SQL mapping file (the file contents are developer-defined mapping sql statement), the entire project can have one or more SQL mapping files

7.mapper: mappers child element node, specify SQL mapping file path, wherein the expression value of the resource attribute sql
path (path-based resource) mapped file
== == Note: element nodes mybatis-config.xml file there is a certain order, node locations, if not ranked in order, then the XML file will complain

2. Next, prepare persistent classes and SQL mapping files
we first define a simple class (user category) user class attributes is a table in our database fields (user table)

public class User {
    private Integer id; //id private String userCode; //用户编码 private String userName; //用户名称 private String userPassword; //用户密码 private Integer gender; //性别 private Date birthday; //出生日期 private String phone; //电话 private String address; //地址 private Integer userRole; //用户角色 private Integer createdBy; //创建者 private Date creationDate; //创建时间 private Integer modifyBy; //更新者 private Date modifyDate; //更新时间 //省略getter,setter方法

== == Note: Under normal circumstances our class database and table names are the same

Next created SQL mapping file, complete the mapping and POJO (Entity class), the document is an XML file

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="cn.smbms.dao.UserMapper"> <!--查询用户表记录数 --> <select id="count" resultType="int"> select count(1) as count from smbms_user </select> </mapper> 

== Experience ==: SQL mapping files are generally corresponds to the corresponding POJO (Entity class), it usually takes the name of POJO + rule Mapper to be named, such as the mapping file we created, called UserMapper.xml ( mapping file is placed under the package dao)

The meaning of each element of the configuration file:
Mapper: root element node mapping file, only one property namespace
namespace: used to distinguish different mapper, a globally unique
select: express query, is one of MyBatis common elements, common properties as follows :
ID attribute: the unique identifier for the namespace
resultType properties: indicates the type of the return value of the SQL statement, SQL statements returned here is of type int

Next, create a test class, adding JUnit4 in the project, create a test class (UserMapperTest.java) test code is as follows:

public class UserMapperTest {
    public static void main(String[] args) throws Exception { //1.读取全局配置文件:mybatis-config.xml String resource="mybatis-config.xml"; //获取mybatis-config.xml文件的输入流 InputStream is= Resources.getResourceAsStream(resource); //2.创建SqlSessionFactory对象 SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is); //创建SqlSession int count=0; SqlSession sqlSession=null; sqlSession=factory.openSession(); count=sqlSession.selectOne("com.smbms.dao.user.UserMapper.count"); //3.关闭SqlSession对象 sqlSession.close(); System.out.println(count); } }

Because every time we have to execute SQL statements to create these objects, so that there will be a lot of redundant code, we put these repetitive code into a tool to extract class, after the call of these tools directly to
creation tool class: MyBatisUtil

public class MyBatisUtil {
    private static SqlSessionFactory factory; static { try { InputStream is= Resources.getResourceAsStream("mybatis-config.xml"); factory=new SqlSessionFactoryBuilder().build(is); }catch (IOException e){ e.printStackTrace(); } } public static SqlSession createSqlSession(){ return factory.openSession(false); } public static void closeSqlSession(SqlSession sqlSession){ if (null!=sqlSession){ sqlSession.close(); } } }

Look at the back of the specific use SQLSession second way

MyBatis basic elements - the core object

==SqlSessionFactoryBuilder==

1.build () method uses the three forms of the configuration information, namely the InputStream (byte stream), Reader (character stream, the Configuration (type)
2.SqlSessionFactoryBuilder great feature is used that is lost

==SqlSessionFactory==

1.openSession () method to get SqlSession instance, openSession () parameter passing true to close the transaction control, automatic submit, false open transaction control mechanisms. The default is true.
2.SqlSessionFactory Once created, it will always present during the entire application is running.

==SqlSession==

1.SqlSession object persistence for performing operations, similar to the JDBC Connection.
2.SqlSession corresponds to a database session, SqlSession not thread safe.
3.SqlSession used in two ways

The first use:
1. Now add a file, select a node Mapper

<!--查询用户列表-->
<select id="getUserList" resultType="com.smbms.pojo.User"> SELECT * FROM USER </select>

2. Writing Test

SqlSession sqlSession=null;
List<User> userList=new ArrayList<User>(); 
try{
    sqlSession= MyBatisUtil.createSqlSession();
    userList=sqlSession.selectList("com.smbms.dao.user.UserMapper.getUserList"); 
}catch (Exception ex){ ex.printStackTrace(); }finally { MyBatisUtil.closeSqlSession(sqlSession); } for (User user : userList) { System.out.println(user.getUserName()); }

The second use:
Based on the above Mapper configuration file
1. Program Interface

public interface UserMapper {
    /** * 获取用户列表 * @return */ List<User> getUserList(); }

2. Writing Test

SqlSession sqlSession=null;
List<User> userList=new ArrayList<User>(); 
try{
    sqlSession= MyBatisUtil.createSqlSession();
    userList=sqlSession.getMapper(UserMapper.class).getUserList();
}catch (Exception ex){
    ex.printStackTrace();
}finally { MyBatisUtil.closeSqlSession(sqlSession); } for (User user : userList) { System.out.println(user.getUserName()); }

Guess you like

Origin www.cnblogs.com/ringqq/p/11597786.html