分享

wiki/mapper3/3.Use.md · abel533 / Mapper

 雨后夜思 2015-11-07

1. 继承通用的Mapper<T>,必须指定泛型<T>

例如下面的例子:

public interface UserInfoMapper extends Mapper<UserInfo> {
  //其他必须手写的接口...

}

一旦继承了Mapper<T>,继承的Mapper就拥有了Mapper<T>所有的通用方法。





2. 泛型(实体类)<T>的类型必须符合要求

实体类按照如下规则和数据库表进行转换,注解全部是JPA中的注解:

  1. 表名默认使用类名,驼峰转下划线(只对大写字母进行处理),如UserInfo默认对应的表名为user_info

  2. 表名可以使用@Table(name = "tableName")进行指定,对不符合第一条默认规则的可以通过这种方式指定表名.

  3. 字段默认和@Column一样,都会作为表字段,表字段默认为Java对象的Field名字驼峰转下划线形式.

  4. 可以使用@Column(name = "fieldName")指定不符合第3条规则的字段名

  5. 使用@Transient注解可以忽略字段,添加该注解的字段不会作为表字段使用.

  6. 建议一定是有一个@Id注解作为主键的字段,可以有多个@Id注解的字段作为联合主键.

  7. 默认情况下,实体类中如果不存在包含@Id注解的字段,所有的字段都会作为主键字段进行使用(这种效率极低).

  8. 实体类可以继承使用,可以参考测试代码中的tk.mybatis.mapper.model.UserLogin2类.

  9. 由于基本类型,如int作为实体类字段时会有默认值0,而且无法消除,所以实体类中建议不要使用基本类型.

  10. @NameStyle注解,用来配置对象名/字段和表名/字段之间的转换方式,该注解优先于全局配置style,可选值:

    • normal:使用实体类名/属性名作为表名/字段名
    • camelhump:这是默认值,驼峰转换为下划线形式
    • uppercase:转换为大写
    • lowercase:转换为小写

通过使用Mapper专用的MyBatis生成器插件可以直接生成符合要求带注解的实体类。









3.主键策略(仅用于insert方法)

通用Mapper还提供了序列(支持Oracle)、UUID(任意数据库,字段长度32)、主键自增(类似Mysql,Hsqldb)三种方式,其中序列和UUID可以配置多个,主键自增只能配置一个。

由于MySql自增主键最常用,所以这里从最简单的配置方式开始。

1.@GeneratedValue(generator = "JDBC")

@Id
@GeneratedValue(generator = "JDBC")
private Integer id;

这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系数据库管理系统的自动递增字段)。 这种情况对应的xml类似下面这样:

<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
    insert into Author (username,password,email,bio)
    values (#{username},#{password},#{email},#{bio})
</insert>

2.@GeneratedValue(strategy = GenerationType.IDENTITY)

这个注解适用于主键自增的情况,支持下面这些数据库:

  • DB2: VALUES IDENTITY_VAL_LOCAL()
  • MYSQL: SELECT LAST_INSERT_ID()
  • SQLSERVER: SELECT SCOPE_IDENTITY()
  • CLOUDSCAPE: VALUES IDENTITY_VAL_LOCAL()
  • DERBY: VALUES IDENTITY_VAL_LOCAL()
  • HSQLDB: CALL IDENTITY()
  • SYBASE: SELECT @@IDENTITY
  • DB2_MF: SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
  • INFORMIX: select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
  • JDBC:这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系数据库管理系统的自动递增字段)。

使用GenerationType.IDENTITY需要在全局配置中配置IDENTITY的参数值,并且需要根据数库配置ORDER属性。

举例如下:

//不限于@Id注解的字段,但是一个实体类中只能存在一个(继承关系中也只能存在一个)
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

对应的XML形式为:

<insert id="insertAuthor">
    <selectKey keyProperty="id" resultType="int" order="AFTER">
      SELECT LAST_INSERT_ID()
    </selectKey>
    insert into Author
      (id, username, password, email,bio, favourite_section)
    values
      (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>

注意<selectKey>中的内容就是IDENTITY参数值对应数据库的SQL

______________________下面这个提醒很重要______________________

重要提醒:IDENTITY除了上面这些选项外,还可以是任意可以执行的SQL,例如MySql的select uuid(),SqlServer的select newid()等等,这种情况下需要保证主键的类型和SQL的返回值一致。

利用这一个特点,我们就可以使用可以回写的UUID值,如果想获得更特殊的主键值,可以自己写函数调用。

______________________上面这个提醒很重要______________________

3.@GeneratedValue(generator = "UUID")

//可以用于任意字符串类型长度超过32位的字段
@GeneratedValue(generator = "UUID")
private String username;

该字段不会回写。这种情况对应类似如下的XML:

<insert id="insertAuthor">
  <bind name="username_bind" value='@java.util.UUID@randomUUID().toString().replace("-", "")' />
  insert into Author
    (id, username, password, email,bio, favourite_section)
  values
    (#{id}, #{username_bind}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>

4.Oracle使用序列

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY,generator = "select SEQ_ID.nextval from dual")
private Integer id;

使用Oracle序列的时候,还需要配置:

<property name="ORDER" value="BEFORE"/>

因为在插入数据库前,需要先获取到序列值,否则会报错。 这种情况对于的xml类似下面这样:

<insert id="insertAuthor">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
  select SEQ_ID.nextval from dual
</selectKey>
insert into Author
  (id, username, password, email,bio, favourite_section)
values
  (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>

4. 将继承的Mapper接口添加到Mybatis配置中

非Spring项目中在mybatis配置文件中配置,如:

<mappers>
  <mapper class="tk.mybatis.mapper.mapper.CountryMapper" />
  <mapper class="tk.mybatis.mapper.mapper.UserInfoMapper" />
  <mapper class="tk.mybatis.mapper.mapper.UserLoginMapper" />
</mappers>

Spring配置方式

如果你在Spring中配置Mapper接口,不需要像上面这样一个个配置,只需要有下面的这个扫描Mapper接口的这个配置即可:

<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.isea533.mybatis.mapper"/>
</bean>

另外因为通用接口都有顶层的接口,所以你还可以用下面的方式进行配置:

<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.**.mapper"/>
  <property name="markerInterface" value="tk.mybatis.mapper.common.Mapper"/>
</bean>

这样配置后,直接继承了Mapper接口的才会被扫描,basePackage可以配置的范围更大。

如果想在Spring4中使用泛型注入,还需要包含Mapper<T>所在的包,具体请看 在Spring4中使用通用Mapper

5. 代码中使用

例如下面这个简单的例子:

SqlSession sqlSession = MybatisHelper.getSqlSession();
try {
    //获取Mapper
    UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
    UserInfo userInfo = new UserInfo();
    userInfo.setUsername("abel533");
    userInfo.setPassword("123456");
    userInfo.setUsertype("2");
    userInfo.setEmail("abel533@gmail.com");
    //新增一条数据
    Assert.assertEquals(1, mapper.insert(userInfo));
    //ID回写,不为空
    Assert.assertNotNull(userInfo.getId());
    //6是当前的ID
    Assert.assertEquals(6, (int)userInfo.getId());
    //通过主键删除新增的数据
    Assert.assertEquals(1,mapper.deleteByPrimaryKey(userInfo));
} finally {
    sqlSession.close();
}

另一个例子:

SqlSession sqlSession = MybatisHelper.getSqlSession();
try {
    //获取Mapper
    CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
    //查询总数
    Assert.assertEquals(183, mapper.selectCount(new Country()));
    //查询100
    Country country = mapper.selectByPrimaryKey(100);
    //根据主键删除
    Assert.assertEquals(1, mapper.deleteByPrimaryKey(100));
    //查询总数
    Assert.assertEquals(182, mapper.selectCount(new Country()));
    //插入
    Assert.assertEquals(1, mapper.insert(country));
} finally {
    sqlSession.close();
}

附:Spring使用相关

直接在需要的地方注入Mapper继承的接口即可,和一般情况下的使用没有区别.

6.其他

如果你的实体是继承Map的,你可能需要将数据库查询的结果从大写下划线形式转换为驼峰形式,你可以搭配下面的拦截器使用:

CameHumpInterceptor - Map结果的Key转为驼峰式


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多