MySQL 表字段类型设计

  1. Boolean 类型 使用,tinyint(1);
  2. 枚举类型,使用tinyint(无需设置);-128 - 127 共256种情况,我感觉一个枚举这么多种情况足以了;比如订单状态很难有256种状态;
  3. 日期类型使用bigint 而不是datetime; bigint 唯一的缺陷就是开发时开发者不方便,但是运行时效率高,json传输时不需要指定格式来回转换,只需要在终端最终的UI上显示时转换一次就可;我们更应该关注的是运行时,而不是开发时。
  4. 无论tinyint还是int,还是bigint,等其它整型 都不要使用无符号的整型;因为有些语言没有无符号的基本类型,比如golang里有 int32和uint32,但是java里只有 integer;整型全部使用无符号,可以兼容所有语言,因为全部的语言都会提供有符号的基本整型;

知道了以上4个基本原则后,我们开始实操:

先建立MySQL表

image

使用 mybatis-generator 来生成 实体类

/**
 * 此表无注释
 */
public class UserTest {
    /**
     * 此列无注释
     */
    private Long userId;

    /**
     * 时间用bigint,单位为秒
     */
    private Long registerTime;

    /**
     * 这里长度设置成1,mybatis会生成boolean
     */
    private Boolean sex;

    /**
     * 长度不需要设置,-128-127共256种情况,存储枚举足以了;
     * -3(游客)、0(普通用户)、4(VIP用户)、2(管理员)、6(超级管理员)
     */
    private Byte userType;

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public Long getRegisterTime() {
        return registerTime;
    }

    public void setRegisterTime(Long registerTime) {
        this.registerTime = registerTime;
    }

    public Boolean getSex() {
        return sex;
    }

    public void setSex(Boolean sex) {
        this.sex = sex;
    }

    public Byte getUserType() {
        return userType;
    }

    public void setUserType(Byte userType) {
        this.userType = userType;
    }
}

然后我们需要创建一个用户类型的 枚举类,方便我们使用:

package com.diandaxia.demo107.enums;

/**
 * 用户类型 枚举
 * -3(游客)、0(普通用户)、4(VIP用户)、2(管理员)、6(超级管理员)
 */
public enum UserType {
    /**
     * 游客
     */
    GUEST(-3),

    /**
     * 普通用户
     */
    GENERAL(0),

    /**
     * vip用户
     */
    VIP(4),

    /**
     * 管理员
     */
    ADMIN(2),

    /**
     * 超级管理员
     */
    SUPER(6);


    /**
     * MySQL里的 tinyint 值
     */
    private Byte tinyInt;


    /**
     * 私有构造方法
     */
    private UserType(Byte tinyInt) {
        this.tinyInt = tinyInt;
    }

    /**
     * 对外公开获取MySQL里的 tinyint 值
     */
    public Byte getTinyInt(){
        return this.tinyInt;
    }

}

image

报错的原因是:GUEST(-3) 这个-3是个常量,整型常量 java默认是 int类型,而我们的tinyInt是Byte类型,int --> byte ,Java 转不了,故报错;需要把常量强制转换一下;

posted on 2024-04-26 11:12  del88  阅读(5)  评论(0编辑  收藏  举报