Realize function
In the development process, it is often encountered that the entire JSON data is stored in the database as a field, but we do not want to use a String to receive it in the corresponding entity table. As shown in the figure below, there is an address field in the database t_user table. A JSON array is stored, and List<Address>
objects are used in the TUserEntity entity to receive it. At this time, a custom TypeHanlder is needed to help us define the JSON serialization and deserialization when entering and exiting the library.
@Data
@TableName("t_user")
public class TUserEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
@TableField(typeHandler = AddressListTypeHandler.class)
private List<Address> address;
}
```
@Data
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
}
```
Define an abstract List to handle TypeHandler, and other types of data may be stored in the List
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public abstract class ListTypeHandler<T> extends BaseTypeHandler<List<T>> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, JsonUtils.toJson(parameter));
}
@Override
public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.wasNull() ? null : JsonUtils.readList(rs.getString(columnName), specificType());
}
@Override
public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.wasNull() ? null : JsonUtils.readList(rs.getString(columnIndex), specificType());
}
@Override
public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.wasNull() ? null : JsonUtils.readList(cs.getString(columnIndex), specificType());
}
protected abstract TypeReference<List<T>> specificType();
Define the AddressListTypeHandler class, if there are other classes inheriting ListTypeHandler
@MappedTypes({List.class})
public class AddressListTypeHandler extends ListTypeHandler<Address> {
@Override
protected TypeReference<List<Address>> specificType() {
return new TypeReference<List<Address>>() {
};
}
}
The JsonUtils.readList() method in jaskson can also use fastjson JSON.parseObject(content, this.specificType())
public static <T> List<T> readList(String json, TypeReference<List<T>> tTypeReference) {
if (json == null || "".equals(json)) {
return null;
}
try {
return mapper.readValue(json,tTypeReference);
} catch (IOException e) {
throw new RuntimeException(e);
}
}