How to serialize/deserialize enum column in spring boot?

378 views Asked by At

I am using spring boot (with bundled jackson and lombok), mybatis and mybatis-plus.

I have a model User with an enum column status:

import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.AllArgsConstructor;

@AllArgsConstructor
public enum UserStatusEnum {
  ACTIVE(1, "active"),
  INACTIVE(0, "inactive");

  @EnumValue
  private Integer dbValue;
  @JsonValue
  private String jsonValue;
}

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "users")
public class User {
  Integer id;
  UserStatusEnum status = UserStatusEnum.ACTIVE;
  String username;
  @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone = "UTC")
  LocalDateTime createdAt = LocalDateTime.now();
}

Database schema is like

CREATE TABLE IF NOT EXISTS users (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    status TINYINT NOT NULL,
    username VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
)  ENGINE=INNODB;
CREATE UNIQUE INDEX users_username_unique ON users (username);
INSERT INTO users (status, username) VALUES (1, "test")

I want to get a user with status of string in json like {"id":1,"status":"active","username":"test","createdAt":"2021-12-08T00:00:00.000Z"} and status is stored in database as TINYINT 1. How can I get that?

I am using mapper:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper extends BaseMapper<User> {}

and make call like:

@Component
public class UserService {
  @Autowired
  UserMapper userMapper;

  public User findUser(Integer id) {
    return userMapper.selectById(id);
  }
}

Right now I would have error like this:

Servlet.service() for servlet [dispatcherServlet] in context with path []
  threw exception [Request processing failed; nested exception is
  org.mybatis.spring.MyBatisSystemException: nested exception is
  org.apache.ibatis.executor.result.ResultMapException:
  Error attempting to get column 'status' from result set.
  Cause: java.lang.IllegalArgumentException:
  No enum constant app.model.user.UserStatusEnum.1] with root cause

java.lang.IllegalArgumentException: No enum constant app.model.user.UserStatusEnum.1
0

There are 0 answers