Contents
  1. 1. 注意事项
  2. 2. API
  3. 3. 搭建过程

https://blog.csdn.net/qq1130169218/article/details/71747429

demo 示例
https://github.com/huangzhenshi/mybatis-mapper

注意事项

  • 实体类需要按照如下规则和数据库表进行转换,注解全部是JPA中的注解,所以我们在maven中添加了它的jar包依赖
  • 表名默认使用类名,驼峰转下划线,如UserInfo默认对应的表名为user_info
  • 表名可以使用@Table(name = “tableName”)进行指定,对不符合第一条默认规则的可以通过这种方式指定表名
  • 字段默认和@Column一样,都会作为表字段,表字段默认为Java对象的Field名字驼峰转下划线形式
  • 可以使用@Column(name = “fieldName”)指定不符合第3条规则的字段名
  • 使用@Transient注解可以忽略字段,添加该注解的字段不会作为表字段使用,建议一定是有一个@Id注解作为主键的字段,可以有多个@Id注解的字段作为联合主键
  • 默认情况下,实体类中如果不存在包含@Id注解的字段,所有的字段都会作为主键字段进行使用(这种效率极低)
  • 实体类可以继承使用
  • 由于基本类型,如int作为实体类字段时会有默认值0,而且无法消除,所以实体类中建议不要使用基本类型

API

/**
* 根据实体中的属性值进行查询,查询条件使用等号
*/
@SelectProvider(type = BaseSelectProvider.class, method = "dynamicSQL")
List<T> select(T record);
VirtualIpBean vipBean = new VirtualIpBean();
vipBean.setBeginTime(new Date());
//(1)mapper基础接口
//select接口
List<VirtualIpBean> vipList = vipMapper.select(vipBean);//根据实体中的属性值进行查询,查询条件使用等号
VirtualIpBean vip = vipMapper.selectOne(vipBean);//根据实体中的属性进行查询,只能有一个返回值,有多个结果是抛出异常,查询条件使用等号
List<VirtualIpBean> vipList2 = vipMapper.selectAll();//查询全部结果,select(null)方法能达到同样的效果
VirtualIpBean vip2 = vipMapper.selectByPrimaryKey(1);//根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
int count = vipMapper.selectCount(vipBean);//根据实体中的属性查询总数,查询条件使用等号
//insert接口
int a = vipMapper.insert(vipBean);//保存一个实体,null的属性也会保存,不会使用数据库默认值
int a1 = vipMapper.insertSelective(vipBean);//保存实体,null的属性不会保存,会使用数据库默认值
//update接口
int b = vipMapper.updateByPrimaryKeySelective(vipBean);//根据主键更新属性不为null的值
int c = vipMapper.updateByPrimaryKey(vipBean);//根据主键更新实体全部字段,null值会被更新
//delete接口
int d = vipMapper.delete(vipBean);//根据实体属性作为条件进行删除,查询条件使用等号
int e = vipMapper.deleteByPrimaryKey(1);//根据主键字段进行删除,方法参数必须包含完整的主键属性
//(2)Example方法
Example example = new Example(VirtualIpBean.class);
example.createCriteria().andEqualTo("id", 1);
example.createCriteria().andLike("val", "1");
//自定义查询
List<VirtualIpBean> vipList3 = vipMapper.selectByExample(example);

搭建过程

  1. 引入依赖

    <dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
    </dependency>
    <!--通用Mapper-->
    <dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper</artifactId>
    <version>3.3.9</version>
    </dependency>
  2. 指定Mapper接口所在包路径

    <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.test.IDao"/>
    </bean>
  3. 标明实体类和表映射关系

    @Data
    @Table(name="user_t")
    public class User {
    @Id
    private Long id;
    private String userName;
    private String password;
    private Short age;
    }
  4. 接口类集成Mapper和指定实体类

    public interface UserDAO extends Mapper<User>{}
  5. 调用

    @Transactional
    public void saveUser(){
    User user = new User();
    user.setUserName("test1736");
    user.setPassword("qwert");
    userDAO.insertSelective(user);
    }
Contents
  1. 1. 注意事项
  2. 2. API
  3. 3. 搭建过程