枚举类的定义概念不做过多解释,这里只说在实际开发中的应用。 使用场景:前端传来的参数为“男”、“女”、“未知”,后台数据库保存的则为tinyint类型的1、2、3;
一、定义枚举类
(这里必须是value变量,mybatisplus里进行了对应的处理)
package com.tanhua.sso.enums;
import com.baomidou.mybatisplus.core.enums.IEnum;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public enum SexEnums implements IEnum<Integer> {
MAN(1, "男"),
WOMAN(2, "女"),
UNKNOWN(3, "未知");
private Integer value;
private String desc;
public Integer getValue() {
this.value = value;
return value;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return desc;
}
}
二、在用户信息里定义枚举类
package com.tanhua.sso.pojo;
import com.tanhua.sso.enums.SexEnums;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo extends BasePojo {
private SexEnums sex;
private Long id;
private Long userId;
private String nickName;
private String logo;
private String tags;
private Integer age;
private String edu;
private String city;
private String birthday;
private String coverPic;
private String industry;
private String income;
private String marriage;
}
三、向数据库插入数据
package com.tanhua.sso.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tanhua.sso.pojo.UserInfo;
public interface UserInfoMapper extends BaseMapper<UserInfo> {
}
====================================================================
package com.tanhua.sso;
import com.tanhua.sso.enums.SexEnums;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.pojo.UserInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class HuanXinTest {
@Resource
private UserInfoMapper userInfoMapper;
@Test
public void testEm(){
UserInfo userInfo=new UserInfo();
userInfo.setSex(SexEnums.UNKNOWN);
userInfo.setCity("北京");
userInfoMapper.insert(userInfo);
}
}
|