只需通过为字段提供默认值来显式声明它:
public record City(Long id, String name, Integer population) {
public City() {
this(0L, "", 0)
}
}
一个重要的说明。BeanPropertyRowMapper扫描 setter/getter 以扩充您的记录实例,因为记录是不可变的,没有 setter 并且它与 Java bean 规范不兼容,您将获取并清空记录。请阅读此SO。创建记录的唯一方法是使用构造函数。所以,你有两个选择:要么使用普通的 java bean,要么实现你的自定义行映射器。
它看起来最简单的方式是这样的:
@Override
public City findById(final Long id) {
final var sql = "SELECT * FROM cities WHERE id = ?";
return jtm.queryForObject(
sql,
new Object[]{ id },
(rs, rowNum) -> new City(
rs.getLong("id"),
rs.getString("name"),
rs.getInt("population")));
}
或者您可以使用反射:
反射 API
以下公共方法将添加到 java.lang.Class:
RecordComponent[] getRecordComponents()
boolean isRecord()
getRecordComponents() 方法返回一个 java.lang.reflect.RecordComponent 对象数组,其中 java.lang.reflect.RecordComponent 是一个新类。此数组的元素对应于记录的组件,其顺序与它们在记录声明中出现的顺序相同。可以从数组中的每个 RecordComponent 中提取附加信息,包括其名称、类型、泛型类型、注释及其访问器方法。
如果给定的类被声明为记录,则方法 isRecord() 返回 true。(与 isEnum() 比较。)
使用这些方法和Class#getConstructor(Class... parameterTypes)和Constructor#newInstance(Object... initargs)您可以动态创建记录。但请记住,反射可能会带来一些开销并影响您的性能。
我添加了一个使用反射和几个测试的RecordRowMapper示例:
package by.slesh.spring.jdbc.core;
import org.springframework.jdbc.IncorrectResultSetColumnCountException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.RecordComponent;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.*;
public class RecordRowMapper<T> implements RowMapper<T> {
private final Constructor<T> ctor;
private final List<Arg> args;
public RecordRowMapper(final Class<T> model) {
if (!model.isRecord()) {
throw new IllegalArgumentException(
model + " should be a record class");
}
final RecordComponent[] components = model.getRecordComponents();
this.args = new ArrayList<>(components.length);
final Class<?>[] argTypes = new Class[components.length];
for (int i = 0; i < components.length; ++i) {
final RecordComponent c = components[i];
this.args.add(new Arg(i, c.getName(), c.getType()));
argTypes[i] = c.getType();
}
try {
this.ctor = model.getConstructor(argTypes);
} catch (NoSuchMethodException e) {
throw new RuntimeException(
"Couldn resolve constructor for types " + Arrays.toString(argTypes));
}
}
@Override
public T mapRow(final ResultSet resultSet, final int rowNumber) throws SQLException {
final var metaData = resultSet.getMetaData();
final int columnCount = metaData.getColumnCount();
if (columnCount < args.size()) {
throw new IncorrectResultSetColumnCountException(
args.size(), columnCount);
}
try {
return ctor.newInstance(extractCtorParams(
resultSet, createPropertyToColumnIndexMap(
metaData, columnCount)));
} catch (InstantiationException
| IllegalAccessException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private Object[] extractCtorParams(
final ResultSet resultSet,
final Map<String, Integer> propertyToColumnIndexMap)
throws SQLException {
final var params = new Object[args.size()];
for (final var arg : args) {
final int columnIndex = propertyToColumnIndexMap.get(arg.name);
params[arg.order] = JdbcUtils.getResultSetValue(
resultSet, columnIndex, arg.type);
}
return params;
}
private Map<String, Integer> createPropertyToColumnIndexMap(
final ResultSetMetaData metaData,
final int columnCount)
throws SQLException {
final Map<String, Integer> columnPropertyToIndexMap = new HashMap<>(columnCount);
for (int columnIndex = 1; columnIndex <= columnCount; ++columnIndex) {
final String propertyName = JdbcUtils.convertUnderscoreNameToPropertyName(
JdbcUtils.lookupColumnName(metaData, columnIndex));
columnPropertyToIndexMap.put(propertyName, columnIndex);
}
return columnPropertyToIndexMap;
}
private static record Arg(int order, String name, Class<?>type) {
}
}