3- Construction MyBatis learning SqlSessionFactory

Each application MyBatis SqlSessionFactory centered way of example, examples can be obtained by SqlSessionFactory SqlSessionFactoryFactory.

SqlSessionFactory is a factory interface rather than implementation class, its task is to create SqlSession

SqlSession similar to a JDBC Connection object

SqlSession offers two modes to create SqlSessionFactory

  1XML configuration (recommended to avoid hard code)

  2 code way

Configuration MyBatis class object exists throughout the life cycle to repeat read and use

MyBatis implementation class provides two SqlSessionFactory

  1 DefaultSqlSessionFactory (currently in use)

  2 SqlSessionManager (currently unused)

 

  1 embodiment constructed using xml

  Typically contains DataSource, TransactionManager, SQL Mapper

  Mapper configuration, introduced for providing SQL and XML definition of mapping rules SQL POJP, which contains the information inside the mapper

  Information analysis program will mybatis-config.xml configuration file parsing to Configuration class object, and then use SqlSessionFactoryBuilder read the object is created for us SqlSessionFactory

  2 embodiment constructed using code

  

 

Creating SqlSession

SqlSession is an interface class, the role of the sentence in the facade, is acting Executor interface

SqlSession like interface in a JDBC interface objects Connection

There are two main purposes SqlSession

  1 get mapper, let mapper to find the namespace and method name of the corresponding SQL, execute and return the results sent to the database

  2 direct result returned by naming information to execute SQL

 

Mapper

Mapper of java interfaces and XML file or annotations together form

  Definition 1 Parameter Type

  2 Description Cache

  3 describe the SQL statement

  4定义查询结果和POJO的映射关系

映射器实现方式有两种,xml、通过代码实现

建议使用XML文件实现

  1Java注解是受限的,功能较少,Mapper更加灵活强大

  2动态SQL写在Java文件中可读性较差

  3通过注解也可以完成SQL定义,但是可读性不佳

 

Mapper的实现由Java接口和一个XML文件构成

  Mapper.xml在mybatis-config.xml中配置过,所以MyBatis读取这个配置文件,生成映射器

  定义一个命名空间为com.xx.mapper.xxMapper的SQLMapper,这个命名空间和定义的接口名称一致

  

Java注解方式实现Mapper

如在Mapper interface方法中假如@Select注解(不适合复杂sql)

 

Guess you like

Origin www.cnblogs.com/alloevil/p/10974659.html