Код: Выделить всё
@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
@Builder
@Entity
@Table(name = "users")
public class UserEntity {
...
Но как насчет того, чтобы сделать еще один шаг вперед и отделить DTO от Интернета?
Например, следующий минимальный пример кода демонстрирует разделение задач с помощью аннотаций JPA, Lombok и Jackson для разных классы, представляющие один и тот же концептуальный объект:
Класс сущности (JPA):
Код: Выделить всё
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String email;
// Getters and setters
}
Код: Выделить всё
import lombok.Data;
import lombok.Builder;
@Data
@Builder
public class UserDTO {
private String username;
private String email;
}
Код: Выделить всё
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserJson {
@JsonProperty("user_name")
private String username;
@JsonProperty("email_address")
private String email;
// Getters and setters
}
Код: Выделить всё
public class UserService {
public UserDTO convertToDTO(UserEntity userEntity) {
return UserDTO.builder()
.username(userEntity.getUsername())
.email(userEntity.getEmail())
.build();
}
public UserJson convertToJson(UserDTO userDTO) {
UserJson userJson = new UserJson();
userJson.setUsername(userDTO.getUsername());
userJson.setEmail(userDTO.getEmail());
return userJson;
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... -from-json
Мобильная версия