• Mybatis04



    title: Mybatis学习04
    date: 2020-01-20 21:48:00
    tags:


    这次的笔记主要是mybatis中的注解

    1、实体类的注解

    • 实体类的注解在mybati的XML文件中配置。

    • 注解的位置应该在setting之后,typeHandlers之前。

    • XML文件中各个配置顺序为:properties,settings,typeAliases,typeHandlers,objectFactory,objectWrapperFactory,reflectorFactory,plugins,environments,databaseIdProvider,mappers

    • 实体类的注解有两种方式

      • 将具体的实体类起一个可以自定义的别名,如:

        <typeAliases>
                <typeAlias type="com.neversettle.domain.User" alias="User"/>
        </typeAliases>
        
      • 将同一包下的所有实体类注解为其名称,如User注解为User及user,官方推荐使用user,实际中User和user都可以,注解方式为:

        <typeAliases>
            <package name="com.neversettle.domain"/>
        </typeAliases>
        

    2、SQL的注解

    • 使用SQL注解需要在mybatis核心文件中注册,将之前的 *Mapper.xml 注册换位类的注册即可,具体如下:

      <mappers>
          <!--        使用XML来实现接口-->
          <!--        <mapper resource="com/neversettle/dao/UserMapper.xml"/>-->
          <!--        使用注解来实现接口-->
          <mapper class="com.neversettle.dao.UserMapper"/>
      </mappers>
      
    • 注解在接口中使用,如下:

      package com.neversettle.dao;
      
      import com.neversettle.domain.User;
      import org.apache.ibatis.annotations.Delete;
      import org.apache.ibatis.annotations.Param;
      import org.apache.ibatis.annotations.Select;
      
      import java.util.List;
      
      public interface UserMapper {
      
          //获取用户列表
          @Select("select * from user")
          List<User> getUserList();
      
          //删除一个用户
          @Delete("delete from user where id = #{id}")
          void deleteUserById(@Param("id")int id);
      }
      
      • 增删改查都对应着一个注解的标签,进行相关的操作都需要使用相应的标签。
      • @Param() 是参数的注解,使用在参数的前方,推荐每个参数都是用注解。

    3、结果集映射

    • 如果实体类中的字段和数据库中的字段名称不一样,则可以使用结果集映射。

    • 结果集映射写在每个接口相应的实现XML中(如UserMapper.xml)

    • 如果只有个别字段不同,则可以只为个别字段映射(相当于注解)

    • 使用方法:

      <resultMap id="Student" type="com.neversettle.domain.Student">
          <result property="passowrd" column="pwd"/>
      </resultMap>
      
      • id为映射的名称,是在SQL语句的返回值类型中所写的名称
      • type为实体类
      • result中的property是实体类中的字段名
      • result中的column是数据库中要映射的字段名
  • 相关阅读:
    JQuery中的回调对象
    CSS中的视觉格式化模型
    css中的选择器
    浅谈css中的position
    python-24: re 模块 之二 re方法及反斜杠
    python-23 xml.etree.ElementTree模块
    python-22 eval json pickle shelve 之间差别
    python-21 os 模块
    python-18: datetime 模块
    python-16: time 模块 之二
  • 原文地址:https://www.cnblogs.com/wuren-best/p/12441546.html
Copyright © 2020-2023  润新知