枚举类enum应用以及注解@transient应用

 

1.增加枚举类

 public enum RightTypeEnum {
        AUTHORITY("访问权限")
        private String type;

        RightTypeEnum(String type) {
            this.type=type;
        }

        public String getType() {
            return type;
        }

    }

 2. 在controller中进行dubug,具体的值见下方截图

       String val = entity.getRight();
        String en = RightTypeEnum.AUTHORITY.toString();
        String ch = RightTypeEnum.AUTHORITY.getType();
        String en1 = RightTypeEnum.valueOf(val).toString();//获取对应变量的英文值
        String ch1 = RightTypeEnum.valueOf(val).getType();//获取中文值

  

3. @transietn使用场景:前台界面需要显示数据库某个字段的中文枚举值,但是数据库该字段是枚举的英文,例如:AUTHORITY("访问权限"),数据库存的是AUTHORITY

解决方案:使用注解@transient,该注解会忽略实体中某个字段与数据库字段的映射,不插入数据到数据库,也就是临时存储数据,可以供前台使用

4.user实体类

@Entity
@Table(name = "t_user")
public class UserEntity implements Serializable
{

    @Id
    @GeneratedValue
    @Column(name = "t_id")
    private Long id;

    @Column(name = "t_right")
    private  String right;

//在不需要映射到数据库的字段上加上@transient注解 @Transient private String rightVal;//该字段用于存枚举字段的中文值 //其他字段省略 public String getRight() { return right; } public void setRight(String right) { this.right = right; } //主要说明此处的作用 public String getRightVal() { String rightValue = RightTypeEnum.valueOf(this.right).getType(); this.rightVal = rightValue; return rightVal; } public void setRightVal(String rightVal) { this.rightVal = rightVal; } }

 5. controller,这样返回的实体就会带有字段 rightVal的值,并且是转换后的中文值

    @RequestMapping(value = "/save",method = RequestMethod.GET)
    public UserEntity save(UserEntity entity)
    {
        return userJPA.save(entity);
    }

 6.http://127.0.0.1:8080/user/save?name=ff&age=23&address=jinan&right=AUTHORITY

    返回实体的值为: 

{"id":7,"name":"ff","age":23,"address":"jinan","right":"AUTHORITY","rightVal":"访问权限"}

猜你喜欢

转载自www.cnblogs.com/Andrew520/p/9571179.html
今日推荐