zoukankan      html  css  js  c++  java
  • 持久层框架:MyBatis 3.2(2)

    每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。

    1.使用Generator自动生成Dao层,Model层和Mapper层。

    MyBatis Generator下载地址:http://www.mybatis.org/generator/

    MyBatis Generator中文介绍:http://generator.sturgeon.mopaas.com/ 

    以下用mybatis-generator-core-1.3.2.jar插件加jdbc数据库连接包自动导出持久层dao包,model包和mapper包。

    需要用到的Java包有: 

    mybatis-generator-core-1.3.2.jar,

    mysql-connector-java-5.1.34.jar,

    ojdbc14-10.2.0.1.0.jar,

    sqljdbc4-4.0.jar。

    配置文件: generator.xml

      1 <?xml version="1.0" encoding="UTF-8"?>
      2 <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
      3 <generatorConfiguration>
      4  <!-- 配置属性文件 用来在配置文件中引入变量 El表达式 -->
      5  <!-- 如果是用cmd方式运行 这里应该写url方式写全路径 因为找不到classpath 对于resource来说 -->
      6  <!-- 
      7  <properties url="file:///D:/workspaces/mybatisGen/bin/generatorConfig.properties"/>
      8  -->
      9  <!-- 数据库驱动包位置 -->
     10  <!-- SQL Server数据驱动包 -->
     11  <classPathEntry location="D:JavaProjectgeneratorsqljdbc4-4.0.jar" /> 
     12  <!-- Oracle数据驱动包 -->
     13  <!--
     14  <classPathEntry location="D:Javam2
    epositorycomoracleojdbc1410.2.0.1.0ojdbc14-10.2.0.1.0.jar" />
     15  -->
     16  <!-- MySQL数据驱动包 -->
     17  <!--
     18  <classPathEntry location="D:JavaProjectgeneratormysql-connector-java-5.1.34.jar" /> 
     19  -->
     20  <!-- 此处指定生成针对MyBatis3的DAO-->
     21  <!-- 
     22   id: 必须配置。这个上下文的惟一标识符。该值将被用在一些错误消息。
     23   defaultModelType:用来定义生成模型类型策略。
     24   1.conditional 默认策略,为每个表生成一个Model class
     25   2.flat:将所有的表中生成一个Model class,即这个类将保存所有表中字段
     26   3.hierarchical :如果表有一个主键,该模型将生成一个主键类,另一个类,用于容纳任何BLOB列在表中,和另一个类,用于容纳其余的字段。这个是一个适当的继承类之间的关系。
     27  targetRuntime:此属性用于指定运行时目标生成的代码。
     28   1.MyBatis3 默认值 将生成对象兼容MyBatis版本3.0和更高版本,和JSE 5.0和更高版本
     29   (例如Java模型和mapper接口将使用泛型类型)。
     30   “by example”方法在这些生成的对象支持几乎无限的动态where子句。
     31   此外,Java对象与这些生成器生成支持许多JSE 5.0特性包括参数化的类型和注释。
     32   2.Ibatis2Java2
     33   3.Ibatis2Java5
     34  -->
     35  <context id="MySQLTables" targetRuntime="MyBatis3" defaultModelType="conditional">
     36  <!-- 
     37  <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />
     38  -->
     39  <!-- 
     40   用来生成注释 
     41   1. suppressAllComments 默认是false 此属性用于指定在生成的代码是否将包括任何注释。如果设置为true 则不生成注释
     42   2. suppressDate 默认是false 此属性用于指定在生成的注释是否将包括MBG代时间戳。
     43  -->
     44  <commentGenerator>
     45   <property name="suppressAllComments" value="true" />
     46  </commentGenerator>
     47  <!-- 数据库链接URL、用户名、密码 -->
     48  <!-- MySQL数据库链接URL、用户名、密码 -->
     49  <!--
     50  <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3310/test" userId="test" password="1234"> 
     51   </jdbcConnection>
     52  -->
     53  <!-- Oracle数据库链接URL、用户名、密码 -->
     54  <!--
     55  <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:orcl" userId="test" password="1234">
     56  </jdbcConnection>
     57  -->
     58  <!-- SQL Server数据库链接URL、用户名、密码 -->
     59   <jdbcConnection driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver" connectionURL="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=test" userId="test" password="1234"> 
     60   </jdbcConnection>
     61  <!-- H2 
     62   <entry key="jdbc.url">jdbc:h2:tcp://localhost/test</entry>
     63   <entry key="jdbc.driver">org.h2.Driver</entry>
     64  -->
     65  <!-- SQLServer2000 
     66   <entry key="jdbc.url">jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=[database]</entry>
     67   <entry key="jdbc.driver">com.microsoft.jdbc.sqlserver.SQLServerDriver</entry>
     68  -->
     69  <!-- SQLServer2005 
     70   <entry key="jdbc.url">jdbc:sqlserver://192.168.0.98:1433;DatabaseName=[database]</entry>
     71   <entry key="jdbc.driver">com.microsoft.sqlserver.jdbc.SQLServerDriver</entry>
     72  -->
     73  <!-- JTDs for SQLServer 
     74   <entry key="jdbc.url">jdbc:jtds:sqlserver://192.168.0.102:1433/[database];tds=8.0;lastupdatecount=true</entry>
     75   <entry key="jdbc.driver">net.sourceforge.jtds.jdbc.Driver</entry>
     76  -->
     77  <!-- PostgreSql
     78   <entry key="jdbc.url">jdbc:postgresql://localhost/[database]</entry>
     79   <entry key="jdbc.driver">org.postgresql.Driver</entry>
     80  -->
     81  <!-- Sybase
     82   <entry key="jdbc.url">jdbc:sybase:Tds:localhost:5007/[database]</entry>
     83   <entry key="jdbc.driver">com.sybase.jdbc.SybDriver</entry>
     84  -->
     85  <!-- DB2 
     86   <entry key="jdbc.url">jdbc:db2://localhost:5000/[database]</entry>
     87   <entry key="jdbc.driver">com.ibm.db2.jdbc.app.DB2Driver</entry>
     88  -->
     89  <!-- HsqlDB 
     90   <entry key="jdbc.url">jdbc:hsqldb:mem:generatorDB</entry>
     91   <entry key="jdbc.driver">org.hsqldb.jdbcDriver</entry>
     92  -->
     93  <!-- Derby 
     94   <entry key="jdbc.url">jdbc:derby://localhost/databaseName</entry>
     95   <entry key="jdbc.driver">org.apache.derby.jdbc.ClientDriver</entry> 
     96  -->
     97  <!-- java类型解析器 可选配置 -->
     98  <!-- 
     99   <javaTypeResolver type=""> 
    100   type属性: 这可用于指定一个用户提供的Java类型解析器。这个类必须实现接口org.mybatis.generator.api。
    101   JavaTypeResolver,必须有一个公共的默认构造函数。属性还可以接受特殊的值默认在这种情况下,将使用默认的实现(这同样的效果不指定类型)。
    102   该标签支持的属性:
    103   forceBigDecimals:默认是false 是否强制使用BigDecimal来表示所有的十进制和数值字段。
    104   •如果规模很大,长度大于18,将使用BigDecimal类型。
    105   •如果其长度为10到18,则Java类型解析器将java.lang.Long来代替了。
    106   •如果长度为5到9,然后Java类型解析器将替换为一个Java.lang.integer。
    107   •如果其长度小于5,则Java类型解析器将以java.lang.Short替代。 
    108  -->
    109  <javaTypeResolver>
    110   <property name="forceBigDecimals" value="false" />
    111  </javaTypeResolver>
    112  <!-- 生成vo对象 -->
    113  <!-- 
    114   < javaModelGenerator >元素用于定义Java模型生成的属性。
    115   Java模型生成器建立主键类,记录类,和查询示例类相匹配的表进行自省。这个元素是所需的子元素<上下文>元素。
    116   支持的属性:
    117   constructorBased:
    118   此属性用于选择是否MyBatis生成器将生成一个类的构造函数,它接受一个值类中的每个字段。同时,SQL结果地图将建成投入使用构造函数而不是“setter”每个字段。
    119   这个属性是只适用于MyBatis3和将被忽略了iBATIS2。
    120   默认值是false。
    121   immutable: 
    122   不可变,此属性用于选择是否MyBatis生成器将产生不可变模型类——这意味着类不会有“setter”方法和构造函数会接受类中每个字段的值。默认为false。
    123   trimStrings:
    124   此属性用于选择MyBatis生成器是否添加代码来修剪的字符字段从数据库返回的空白空间。
    125   这很有用,如果您的数据库将数据存储在字符字段而不是VARCHAR字段。MyBatis生成器将插入代码来削减字符字段。
    126   默认值是false。
    127  -->
    128  <!-- 生成实体类的包名和位置,这里配置将生成的实体类放在com.ouc.model这个包下 -->
    129  <javaModelGenerator targetPackage="com.ouc.model" targetProject="D:JavaProjectgeneratorsrc">
    130   <property name="enableSubPackages" value="true" />
    131   <property name="trimStrings" value="true" />
    132  </javaModelGenerator>
    133  <!-- 生成用于查询的mapping对象 -->
    134  <!-- 生成的SQL映射文件包名和位置,这里配置将生成的SQL映射文件放在com.ouc.mapping这个包下 -->
    135  <sqlMapGenerator targetPackage="com.ouc.mapping" targetProject="D:JavaProjectgeneratorsrc">
    136   <property name="enableSubPackages" value="true" />
    137  </sqlMapGenerator>
    138  <!-- 生成DAO的类文件以及配置文件 -->
    139  <!-- 
    140   < javaClientGenerator >元素是用来定义Java客户机代码生成器的属性。
    141   Java客户机生成器用来建立Java接口和类,以便可以方便地使用生成的Java模型和XML映射文件。
    142   对于iBATIS2目标环境,这些生成的对象采用形式的DAO接口和实现类。
    143   对于MyBatis,生成的对象采用mapper形式的接口。
    144   这个元素是一个可选的子元素。
    145   如果你不指定这个元素,MyBatis生成器(MBG)不会生成Java客户端接口和类。
    146   其中的type属性:
    147   如果targetRuntime 为MyBatis3
    148   XMLMAPPER:生成的对象将Java接口MyBatis 3.x mapper基础设施。接口将会依赖生成的XML映射器文件。一般都是使用这个XMLMAPPER.
    149  -->
    150  <!-- 生成DAO的包名和位置,这里配置将生成的dao类放在com.ouc.dao这个包下 -->
    151  <javaClientGenerator type="XMLMAPPER" targetPackage="com.ouc.dao" targetProject="D:JavaProjectgeneratorsrc">
    152   <property name="enableSubPackages" value="true" />
    153  </javaClientGenerator>
    154  <!-- 
    155   <table>元素用于选择数据库中的一个表。选择的表将导致为每个表生成以下对象:
    156   •一个MyBatis / iBATIS•格式化的SQL的映射文件
    157   •一组类,形成了“模型”表包括:
    158   •一个类来匹配•表的主键(如果表有一个主键)。
    159   •表中字段匹配的,不是在主键,而非BLOB字段。这个类将扩展主键,如果有一个。
    160   •一个类来持有任何表中的BLOB字段(如果有的话)。这个类将扩展其中一个的前面两个类取决于表的配置。
    161   •一个类,用于生成动态where子句,在不同的“by Example”方法(selectByExample,deleteByExample)。
    162   •(可选)DAO接口和类
    163   tableName:必须配置 指定表的名称
    164   domainObjectName:生成javabean对象的基本名称。如果未指定,MBG将自动基于表名生成。
    165   这个名字(无论是在这里指定,或自动生成)将被用来作为域类名和DAO类的名字。
    166   enableInsert:是否生成插入语句。默认是true
    167   enableSelectByPrimaryKey:是否通过主键生成选择语句。不管是否有这种设置,如果该表没有一个主键将不会生成。
    168   enableUpdateByPrimaryKey:是否通过主键生成更新语句。如果该表没有主键,不管是否设置该属性,语句将不会生成。
    169   enableDeleteByPrimaryKey:是否通过主键生成删除语句。如果该表没有主键,不管这种设置该属性,语句将不会生成。
    170   enableDeleteByExample:是否通过example对象生成删除语句。这个声明使得许多不同的动态删除在运行时生成。
    171   enableCountByExample:是否通过example对象生成计算行数语句。该语句将返回一个表中的行数相匹配的example。
    172   enableUpdateByExample:是否通过example对象生成更新语句。该语句将更新一个表中相匹配的记录。
    173   selectByPrimaryKeyQueryId:这个值将被添加到选择列表中选择通过主键的声明在本表格:“' <值>作为QUERYID”。这可以用于识别查询在DBA在运行时跟踪工具。如果你需使用,你应该指定一个唯一的id为每个不同的查询生成MBG。
    174   selectByExampleQueryId:这个值将被添加到选择列表中选择通过例子的声明在本表格:“' <值>作为QUERYID”。这可以用于识别查询在DBA在运行时跟踪工具。如果你需使用,你应该指定一个唯一的id为每个不同的查询生成MBG。
    175   enableSelectByExample:是否应该生成通过example的选择语句。这个声明使得许多不同的动态查询是在运行时生成。
    176   modelType:此属性用于覆盖默认的模型类型,如果你想对这张表这么做。如果未指定,MBG将生成的域对象基于上下文默认的模型类型。
    177   该模型类型定义了如何将生成MBG域类。
    178   一些模型类型MBG将生成一个单一的域类为每个表,和其他可能产生不同的类MBG取决于表的结构。
    179   escapeWildcards:排除通配符。这意味着无论SQL通配符(' _ '和' % ')的模式和表名都应该避免在搜寻列。
    180   这是一些驱动要求如果模式或表包含一个SQL通配符(例如,如果一个表的名字是MY_TABLE,一些驱动要求的下划线字符进行转义)。
    181  -->
    182  <!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
    183  <table tableName="V_SupplyUser" domainObjectName="VSupplyUser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
    184  <table tableName="WJ_GateList" domainObjectName="WJGateList" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
    185  </context>
    186 </generatorConfiguration>
    配置文件

    打开cmd命令行,转到配置文件所在的文件下,执行如下生成语句:

    1
    java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite

    命令执行完毕,可以看到对应路径下生成dao包,model包和mapper包文件。

    2.MyBatis框架整合

    1)MyBatis使用参数配置:sqlMapConfig.xml。

    ① 缓存配置(Cache):cacheEnabled:全局开关:默认是true,如果它配成false,其余各个Mapper XML文件配成支持cache也没用。

    ② 延迟加载:

    lazyLoadingEnabled:true使用延迟加载,false禁用延迟加载,默认为true,当禁用时, 所有关联对象都会即时加载。 

    aggressiveLazyLoading:true启用时,当延迟加载开启时访问对象中一个懒对象属性时,将完全加载这个对象的所有懒对象属性。false,当延迟加载时,按需加载对象属性(即访问对象中一个懒对象属性,不会加载对象中其他的懒对象属性)。默认为true。

    ③ multipleResultSetsEnabled:允许和不允许单条语句返回多个数据集(取决于驱动需求)。默认为true。

    ④ useColumnLabel:使用列标签代替列名称。不同的驱动器有不同的做法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。

    ⑤ useGeneratedKeys:允许JDBC生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。

    ⑥ autoMappingBehavior:指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。

    ⑦ defaultExecutorType:配置和设定执行器,SIMPLE执行器执行其它语句。REUSE执行器可能重复使用prepared statements语句,BATCH执行器可以重复执行语句和批量更新。

    ⑧ defaultStatementTimeout:设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时。

    完整sqlMapConfig.xml配置文件如下:

     1 1
     2 2
     3 3
     4 4
     5 5
     6 6
     7 7
     8 8
     9 9
    10 10
    11 11
    12 12
    13 13
    14 14
    15 15
    16 16
    17 17
    18 18
    19 19
    20 20
    21 21
    22 22
    23 23
    24 24
    25 25
    26 26
    27 27
    28 28
    29 29
    30 30
    31 31
    32 32
    33 33
    34 <?xml version="1.0" encoding="UTF-8" ?>
    35 <!DOCTYPE configuration
    36 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    37 "http://mybatis.org/dtd/mybatis-3-config.dtd">
    38 <configuration>
    39 <settings>
    40 <setting name="cacheEnabled" value="true" />
    41 <setting name="lazyLoadingEnabled" value="true" />
    42 <setting name="multipleResultSetsEnabled" value="true" />
    43 <setting name="useColumnLabel" value="true" />
    44 <setting name="useGeneratedKeys" value="false" />
    45 <setting name="autoMappingBehavior" value="PARTIAL" />
    46 <setting name="defaultExecutorType" value="SIMPLE" /><!-- SIMPLE REUSE BATCH -->
    47 <!-- <setting name="defaultExecutorType" value="BATCH" /> -->
    48 <setting name="defaultStatementTimeout" value="" />
    49 <setting name="safeRowBoundsEnabled" value="false" />
    50 <setting name="mapUnderscoreToCamelCase" value="false" />
    51 <setting name="localCacheScope" value="SESSION" />
    52 <!-- <setting name="jdbcTypeForNull" value="OTHER" /> -->
    53 <setting name="jdbcTypeForNull" value="NULL" />
    54 <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
    55 </settings>
    56 <typeAliases>
    57 <!-- 模块 -->
    58 <typeAlias alias="User" type="com.ouc.mkhl.platform.authority.model.User"/> 
    59 <typeAlias alias="Role" type="com.ouc.mkhl.platform.authority.model.Role"/>
    60 <typeAlias alias="Equipment" type="com.ouc.mkhl.platform.basedata.model.Equipment"/>
    61 <typeAlias alias="Factory" type="com.ouc.mkhl.platform.basedata.model.Factory"/>
    62 </typeAliases>
    63 <typeHandlers>
    64 <typeHandler handler="com.ouc.openplatform.dao.mybatis.SerializableTypeHandler"/>
    65 </typeHandlers>
    66 </configuration>
    配置文件

    序列化特殊值处理:SerializableTypeHandler

     1 2
     2 3
     3 4
     4 5
     5 6
     6 7
     7 8
     8 9
     9 10
    10 11
    11 12
    12 13
    13 14
    14 15
    15 16
    16 17
    17 18
    18 19
    19 20
    20 21
    21 22
    22 23
    23 24
    24 25
    25 26
    26 27
    27 28
    28 29
    29 30
    30 31
    31 32
    32 33
    33 package com.ouc.openplatform.dao.mybatis;
    34 import java.io.Serializable;
    35 import java.sql.CallableStatement;
    36 import java.sql.PreparedStatement;
    37 import java.sql.ResultSet;
    38 import java.sql.SQLException;
    39 import org.apache.ibatis.type.BaseTypeHandler;
    40 import org.apache.ibatis.type.JdbcType;
    41 /**
    42 * @author WuPing
    43 */
    44 public class SerializableTypeHandler extends BaseTypeHandler<Serializable> {
    45 @Override
    46 public void setNonNullParameter(PreparedStatement ps, int i, Serializable parameter, JdbcType jdbcType)
    47 throws SQLException {
    48 ps.setObject(i, parameter);
    49 }
    50 @Override
    51 public Serializable getNullableResult(ResultSet rs, String columnName)
    52 throws SQLException {
    53 return (Serializable)rs.getObject(columnName);
    54 }
    55 @Override
    56 public Serializable getNullableResult(ResultSet rs, int columnIndex)
    57 throws SQLException {
    58 return (Serializable)rs.getObject(columnIndex);
    59 }
    60 @Override
    61 public Serializable getNullableResult(CallableStatement cs, int columnIndex)
    62 throws SQLException {
    63 return (Serializable)cs.getObject(columnIndex);
    64 }
    65 }
    代码示例

    2)结果集resultMap:

    MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。在MyBatis进行查询映射的时候,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。当提供的返回类型属性是resultType的时候,MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。所以其实MyBatis的每一个查询映射的返回类型都是ResultMap,只是当我们提供的返回类型属性是resultType的时候,MyBatis对自动的给我们把对应的值赋给resultType所指定对象的属性,而当我们提供的返回类型是resultMap的时候,因为Map不能很好表示领域模型,我们就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用。

    示例:UserBaseResultMap

     1 <resultMap id="UserBaseResultMap" type="User" >
     2 <id column="id" property="id" jdbcType="INTEGER" />
     3 <result column="userName" property="userName" jdbcType="VARCHAR" />
     4 <result column="password" property="password" jdbcType="VARCHAR" />
     5 <result column="email" property="email" jdbcType="VARCHAR" />
     6 <result column="trueName" property="trueName" jdbcType="VARCHAR" />
     7 <result column="sex" property="sex" jdbcType="VARCHAR" />
     8 <result column="age" property="age" jdbcType="INTEGER" />
     9 <result column="telephone" property="telephone" jdbcType="VARCHAR" />
    10 </resultMap>
    示例

    model类:User

     1 package com.ouc.mkhl.platform.authority.model;
     2 import java.io.Serializable;
     3 //用户信息
     4 public class User implements Serializable {
     5  private static final long serialVersionUID = 1098321123L;
     6  private Integer id; //用户Id
     7  private String userName; //用户名
     8  private String password; //未加密密码
     9  private String email; //邮箱
    10  private String trueName; //真实姓名
    11  private String sex; //性别
    12  private Integer age; //年龄
    13  private String telephone; //手机
    14  public Integer getId() {
    15  return id;
    16  }
    17  public void setId(Integer id) {
    18  this.id = id;
    19  }
    20  public String getUserName() {
    21  return userName;
    22  }
    23  public void setUserName(String userName) {
    24  this.userName = userName == null ? null : userName.trim();
    25  }
    26  public String getPassword() {
    27  return password;
    28  }
    29  public void setPassword(String password) {
    30  this.password = password == null ? null : password.trim();
    31  }
    32  public String getEmail() {
    33  return email;
    34  }
    35  public void setEmail(String email) {
    36  this.email = email == null ? null : email.trim();
    37  }
    38  public String getTrueName() {
    39  return trueName;
    40  }
    41  public void setTrueName(String trueName) {
    42  this.trueName = trueName == null ? null : trueName.trim();
    43  }
    44  public String getSex() {
    45  return sex;
    46  }
    47  public void setSex(String sex) {
    48  this.sex = sex == null ? null : sex.trim();
    49  }
    50  public Integer getAge() {
    51  return age;
    52  }
    53  public void setAge(Integer age) {
    54  this.age = age;
    55  }
    56  public String getTelephone() {
    57  return telephone;
    58  }
    59  public void setTelephone(String telephone) {
    60  this.telephone = telephone == null ? null : telephone.trim();
    61  }
    62 }
    示例

    3)增删改查:

    (1)select查询: 

    ① id:在这个模式下唯一的标识符,可被其它语句引用。

    ② parameterType:传给此语句的参数的完整类名或别名。

    ③ resultType:语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用)

    ④ resultMap:引用的外部resultMap名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用)

    ⑤ flushCache:如果设为true,则会在每次语句调用的时候就会清空缓存。select语句默认设为false。

    ⑥ useCache:如果设为true,则语句的结果集将被缓存。select语句默认设为false。

    ⑦ timeout :设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定。

    示例:查询所有用户信息:selectUsers

    1 <select id="selectUsers" resultMap="UserBaseResultMap">
    2 select id,userName,email from user
    3 </select>
    SQL示例

    (2) insert插入:saveUser

    此处数据库表使用主键自增,主键为id。

    ① fetchSize:设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定。

    ② statementType:statement,preparedstatement,callablestatement。预准备语句、可调用语句。

    ③ useGeneratedKeys:使用JDBC的getGeneratedKeys方法来获取数据库自己生成的主键(MySQL、SQLSERVER等关系型数据库会有自动生成的字段)。

    ④ keyProperty:标识一个将要被MyBatis设置进getGeneratedKeys的key所返回的值,或者为insert语句使用一个selectKey子元素。

    1 <insert id="saveUser" parameterType="User" >
    2 insert into user (userName, password, email, trueName, sex, age, telephone)
    3 values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
    4 #{email,jdbcType=VARCHAR}, #{trueName,jdbcType=VARCHAR}, 
    5 #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{telephone,jdbcType=VARCHAR})
    6 </insert>
    代码示例

    (3)update更新:动态更新SQL:updateUser

     1 <update id="updateUser" parameterType="User" >
     2 update user
     3 <set >
     4 <if test="userName != null" >
     5 userName = #{userName,jdbcType=VARCHAR},
     6 </if>
     7 <if test="password != null" >
     8 password = #{password,jdbcType=VARCHAR},
     9 </if>
    10 <if test="email != null" >
    11 email = #{email,jdbcType=VARCHAR},
    12 </if>
    13 <if test="trueName != null" >
    14 trueName = #{trueName,jdbcType=VARCHAR},
    15 </if>
    16 <if test="sex != null" >
    17 sex = #{sex,jdbcType=VARCHAR},
    18 </if>
    19 <if test="age != null" >
    20 age = #{age,jdbcType=INTEGER},
    21 </if>
    22 <if test="telephone != null" >
    23 telephone = #{telephone,jdbcType=VARCHAR},
    24 </if>
    25 </set>
    26 where id = #{id,jdbcType=INTEGER}
    27 </update>
    示例

    (4)delete删除:deleteUser

    1 <delete id="deleteUser" parameterType="Integer">
    2 delete from user
    3 where id = #{id,jdbcType=INTEGER}
    4 </delete>
    示例

    (5)sql: Sql元素用来定义一个可以复用的SQL语句段,供其它语句调用。

    1 <sql id="UserBaseColumnList" >
    2 userName, password, email, telephone
    3 </sql>
    4 <select id="getUsers" resultMap="UserBaseResultMap">
    5 select 
    6 <include refid="UserBaseColumnList" />
    7 from user
    8 </select>
    示例

    6)参数:parameters:MyBatis可以使用基本数据类型和Java的复杂数据类型。

    基本数据类型,String,int,date等。

    使用基本数据类型,只能提供一个参数,所以需要使用Java实体类,或Map类型做参数类型。通过#{}可以直接得到其属性。

    ① 基本数据类型参数:String

    1 public User getUserByName(String name); // 根据用户名获取用户信息
    Java代码
    1 <insert id="saveUser" parameterType="User" >
    2 insert into user (userName, password, email, trueName, sex, age, telephone)
    3 values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
    4 #{email,jdbcType=VARCHAR}, #{trueName,jdbcType=VARCHAR}, 
    5 #{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{telephone,jdbcType=VARCHAR})
    6 </insert>
    Java实体类参数 :User
    1 public int saveUser(User user); // 插入用户信息
    Java代码示例
     1 <select id="selectChildGroupTotalNum" resultType="Integer" >
     2 select count(*) from groupinfo
     3 <trim prefix="WHERE" prefixOverrides="AND|OR">
     4 and id in 
     5 <foreach collection="idStr" item="ids" open="(" separator="," close=")"> 
     6 #{ids} 
     7 </foreach> 
     8 <if test="name!= null and name!='' " >
     9 and name LIKE CONCAT(CONCAT('%', #{name}),'%')
    10 </if>
    11 <if test="description!= null and description!='' " >
    12 AND description LIKE CONCAT(CONCAT('%', #{description}),'%')
    13 </if>
    14 <if test="type != null and type!=-1 " >
    15 AND type = #{type,jdbcType=INTEGER}
    16 </if>
    17 <if test="category != null and category!=-1 " >
    18 AND category = #{category,jdbcType=INTEGER}
    19 </if>
    20 </trim> 
    21 </select>
    Map参数:Map<String, Object> recordMap
    1 //获取子组总记录数
    2 public int selectChildGroupTotalNum(Map<String, Object> recordMap); 
    3 Map<String, Object> recordMap = new HashMap<String, Object>();
    4 recordMap.put("idStr", group.getChildgroupids().split(","));
    5 recordMap.put("name", name);
    6 recordMap.put("description", description);
    7 recordMap.put("type", -1);
    8 recordMap.put("category", -1);
    9 childGroupTotalNum = groupDao.selectChildGroupTotalNum(recordMap);
    Java代码

    ④ 多参数:

    方法一:按顺序传递参数。

    1 <!-- 根据参数名查询参数 -->
    2 <select id="selectSensorNobySensorName" resultType="Integer" useCache="false" flushCache="true">
    3 select SensorNo from sensorconfig 
    4 where Name = #{0} and TestunitNo = #{1} and LABCODE = #{2}
    5 </select>
    SQL示例
    1 //根据参数名查询参数ID
    2 public int selectSensorNobySensorName(String sensorName, int testUnitNo, String 
    Java代码

    方法二:接口参数上添加@Param注解。

     1 <select id="selectByUserNameAndVCode" resultMap="UserBaseResultMap">
     2 select id, userName from user
     3 <trim prefix="WHERE" prefixOverrides="AND|OR">
     4 <if test="userName!= null and userName!='' ">
     5 and userName LIKE CONCAT(CONCAT('%', #{userName}),'%')
     6 </if>
     7 <if test="supplierno!= null and supplierno!='' ">
     8 and supplierNo LIKE CONCAT(CONCAT('%', #{supplierno}),'%')
     9 </if> 
    10 and supplierNo != 'test'
    11 </trim>
    12 LIMIT #{startIndex},#{pageSize}
    13 </select>
    SQL示例
    1 // 根据用户名和V码查询用户信息
    2 public List<User> selectByUserNameAndVCode(
    3 @Param("userName") String userName,
    4 @Param("supplierno") String supplierno,
    5 @Param("startIndex") int startIndex, @Param("pageSize") int pageSize);
    Java代码

    4)动态SQL语句:

    selectKey标签,if标签,if + where的条件判断,if + set的更新语句,if + trim代替where/set标签,trim代替set,choose (when, otherwise),foreach标签。动态SQL语句算是MyBatis最灵活的部分吧,用好了非常方便。

    示例:selectTotalNumByAccountType

     1 2
     2 3
     3 4
     4 5
     5 6
     6 7
     7 8
     8 9
     9 10
    10 11
    11 12
    12 13
    13 14
    14 15
    15 16
    16 17
    17 18
    18 <select id="selectTotalNumByAccountType" resultType="Integer" >
    19 select count(*) from user
    20 <trim prefix="WHERE" prefixOverrides="AND|OR">
    21 and id not in 
    22 <foreach collection="idStr" item="ids" open="(" separator="," close=")"> 
    23 #{ids} 
    24 </foreach> 
    25 <if test="userName!= null and userName!='' ">
    26 and userName LIKE CONCAT(CONCAT('%', #{userName}),'%')
    27 </if>
    28 <if test="supplierno!= null and supplierno!='' ">
    29 and supplierNo LIKE CONCAT(CONCAT('%', #{supplierno}),'%')
    30 </if> 
    31 <if test="trueName!= null and trueName!='' ">
    32 and trueName LIKE CONCAT(CONCAT('%', #{trueName}),'%')
    33 </if>
    34 AND accountType = #{accountType}
    35 </trim></select>
    代码示例

    ④ 多参数:

    方法一:按顺序传递参数。

  • 相关阅读:
    理论四:接口隔离原则有哪三种应用?原则中的“接口”该如何理解?
    gunicorn 配置文件
    转载——gunicorn的实践经验
    pympler 模块
    类属性的名称空间
    django——实现事务
    django-apscheduler报错——Run time of job …… next run at: ……)” was missed by
    阿里云连接数据库服务
    第十三周总结
    IDEA常用模板
  • 原文地址:https://www.cnblogs.com/yang82/p/6911493.html
Copyright © 2011-2022 走看看