Java--MybatisPlus表和列;自定义SQL(三)

阅读前可先参考

https://blog.csdn.net/MinggeQingchun/article/details/126521908

https://blog.csdn.net/MinggeQingchun/article/details/126533536

一、表和列 

注解 | MyBatis-Plus

1、表名

@TableName 注解

定义实体类时,默认需要和数据库中的表名保持一致;如果不一致可以使用 @TableName注解来进行说明

@TableName(value = "数据库表名")

创建表 user_address

DROP TABLE IF EXISTS user_address;

CREATE TABLE user_address(
		address_id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
		address_provice varchar(50) NULL DEFAULT NULL COMMENT '省份',
		address_city varchar(50) NULL DEFAULT NULL COMMENT '城市',
		address_street varchar(50) NULL DEFAULT NULL COMMENT '街道',
		address_code int(11) NULL DEFAULT NULL COMMENT '行政编码',
		PRIMARY KEY (address_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

编写entity实体类

/**
 * @TableName(value="表名")
 * 位置:在类定义的上面
 */
@TableName(value = "user_address")
public class Address {

    //指定主键
    @TableId(value="address_id",type  = IdType.AUTO)
    private Integer id;
    private String provice;
    private String city;
    private String street;
    private String code;

}
属性类型必须指定默认值描述
valueString""表名
schemaString""schema
keepGlobalPrefixbooleanfalse是否保持使用全局的 tablePrefix 的值(当全局 tablePrefix 生效时)
resultMapString""xml 中 resultMap 的 id(用于满足特定类型的实体类对象绑定)
autoResultMapbooleanfalse是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建与注入)
excludePropertyString[]{}需要排除的属性名 @since 3.3.1

2、列名

@TableField 注解

/**
     * @TableField : 指定属性和列名的对应关系。
     *    属性: value 指定列名
     */
    @TableField(value = "address_provice")
    private String provice;
    @TableField(value = "address_city")
    private String city;
    @TableField(value = "address_street")
    private String street;
    @TableField(value = "address_code")
    private String code;
属性类型必须指定默认值描述
valueString""数据库字段名
existbooleantrue是否为数据库表字段
conditionString""字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s}参考(opens new window)
updateString""字段 update set 部分注入,例如:当在version字段上注解update="%s+1" 表示更新时会 set version=version+1 (该属性优先级高于 el 属性)
insertStrategyEnumFieldStrategy.DEFAULT举例:NOT_NULL
insert into table_a(<if test="columnProperty != null">column</if>) values (<if test="columnProperty != null">#{columnProperty}</if>)
updateStrategyEnumFieldStrategy.DEFAULT举例:IGNORED
update table_a set column=#{columnProperty}
whereStrategyEnumFieldStrategy.DEFAULT举例:NOT_EMPTY
where <if test="columnProperty != null and columnProperty!=''">column=#{columnProperty}</if>
fillEnumFieldFill.DEFAULT字段自动填充策略
selectbooleantrue是否进行 select 查询
keepGlobalFormatbooleanfalse是否保持使用全局的 format 进行处理
jdbcTypeJdbcTypeJdbcType.UNDEFINEDJDBC 类型 (该默认值不代表会按照该值生效)
typeHandlerClass<? extends TypeHandler>UnknownTypeHandler.class类型处理器 (该默认值不代表会按照该值生效)
numericScaleString""指定小数点后保留的位数

3、主键

@TableId 注解

//指定主键
    @TableId(value="address_id",type  = IdType.AUTO)
    private Integer id;

IdType 类型 

public enum IdType {
    AUTO(0),
    NONE(1),
    INPUT(2),
    ASSIGN_ID(3),
    ASSIGN_UUID(4);
}

application.yml配置文件设置

mybatis-plus:
  global-config:
    db-config:
      # id生成策略 auto为数据库自增
      id-type: auto
描述
AUTO数据库 ID 自增
NONE无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
INPUTinsert 前自行 set 主键值
ASSIGN_ID分配 ID(主键类型为 Number(Long 和 Integer)或 String)(since 3.3.0),使用接口IdentifierGenerator的方法nextId(默认实现类为DefaultIdentifierGenerator雪花算法)
ASSIGN_UUID分配 UUID,主键类型为 String(since 3.3.0),使用接口IdentifierGenerator的方法nextUUID(默认 default 方法)
ID_WORKER分布式全局唯一 ID 长整型类型(please use ASSIGN_ID)
UUID32 位 UUID 字符串(please use ASSIGN_UUID)
ID_WORKER_STR分布式全局唯一 ID 字符串类型(please use ASSIGN_ID)

测试

@Test
    public void testInsert(){
        Address address  = new Address();
        address.setCity("上海");
        address.setStreet("南京路");
        address.setCode("020");

        //INSERT INTO user_address ( address_city, address_street, address_code ) VALUES ( ?, ?, ? )
        int rows = addressMapper.insert(address);
        System.out.println("insert address结果:"+rows);
    }

4、驼峰命名

默认情况下MP会开启字段名列名的驼峰映射, 即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java 属性名 aColumn(驼峰命名) 的类似映射

application.yml配置文件设置

mybatis-plus:
  configuration:
	#是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java 属性名 aColumn(驼峰命名) 的类似映射
    map-underscore-to-camel-case: false

1、建表goods

DROP TABLE IF EXISTS goods;

CREATE TABLE goods(
		good_id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
		good_name varchar(50) NULL DEFAULT NULL COMMENT '商品名字',
		good_cate varchar(50) NULL DEFAULT NULL COMMENT '商品类别',
		PRIMARY KEY (good_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、创建实体类entity

@TableName(value = "goods")
@Data
public class Goods {
    //定义属性
    @TableId(value="good_id",type = IdType.AUTO)
    private Integer goodId;
    private String goodName;
    private String goodCate;

    @Override
    public String toString() {
        return "Goods{" +
                "goodId=" + goodId +
                ", goodName='" + goodName + '\'' +
                ", goodCate='" + goodCate + '\'' +
                '}';
    }
}

3、创建mapper

/**
 * 自定义Mapper,就是Dao接口
 * 1、要实现BaseMapper
 * 2、指定实体类
 *
 * BaseMapper是MP框架中的对象,定义19个操作方法(CRUD)
 */
public interface GoodMapper extends BaseMapper<Goods> {
}

4、测试

@Test
    public void testInsert(){
        Goods goods = new Goods();
        goods.setGoodName("iPhone 12");
        goods.setGoodCate("手机");

        //INSERT INTO goods ( good_name, good_cate ) VALUES ( ?, ? )
        int rows = goodMapper.insert(goods);
        System.out.println("insert good结果:"+rows);
    }

二、自定义SQL

1、建表

DROP TABLE IF EXISTS student;

CREATE TABLE student(
		id int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
		name varchar(50) NULL DEFAULT NULL COMMENT '学生名字',
		age int(11) NULL DEFAULT NULL COMMENT '年龄',
		email varchar(50) NULL DEFAULT NULL COMMENT '邮箱',
		status int(11) NULL DEFAULT NULL COMMENT '状态',
		PRIMARY KEY (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、创建实体entity

@Data
public class Student {
    //定义属性
    @TableId(value="id",type = IdType.AUTO)
    private Integer id;
    private String name;
    private Integer age;
    private String email;
    private Integer status;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", status=" + status +
                '}';
    }
}

3、创建mapper

/**
 * 自定义Sql
 */
public interface StudentMapper extends BaseMapper<Student> {
    //自定义方法
    public int insertStudent(Student student);
    public Student selectStudentById(Integer id);
    public List<Student> selectByName(String name);
}

4、创建SQL映射xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.company.mapper.StudentMapper">
    <insert id="insertStudent">
        insert into student(name,age,email,status) values(#{name},#{age},#{email},#{status})
    </insert>

    <select id="selectStudentById" resultType="com.company.entity.Student">
        select id,name,age,email,status from student where id=#{studentId}
    </select>

    <select id="selectByName" resultType="com.company.entity.Student">
        select id,name,age,email,status from student where name=#{name}
    </select>
</mapper>

5、配置xml文件

mybatis-plus:
  #配置xml文件位置
  mapper-locations: classpath*:mapper/*Mapper.xml

6、测试

@Test
    public void testInsertStudent(){
        Student student  = new Student();
        student.setName("zhangsan");
        student.setAge(18);
        student.setEmail("zhangsan@163.com");
        student.setStatus(2);
        int rows  = studentMapper.insert(student);
        System.out.println("insert Student rows:"+rows);
    }

    @Test
    public void testSelect(){
        Student student = studentMapper.selectById(1);
        System.out.println("testSelect:"+student);
    }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值