【发布时间】:2021-11-11 09:05:51
【问题描述】:
我正在使用 JPA 更新表。 Postgres 是数据库。有一个类型为 String[] 的字段。通过 API 更新时,其他字段正在更新。但是这个 String[] 字段正在更新为 null 。我已经通过参考 https://www.baeldung.com/java-hibernate-map-postgresql-array 来实现。任何帮助表示赞赏
CustomMapper.java
public class CustomStringArrayType implements UserType {
@Override
public int[] sqlTypes() {
return new int[]{Types.ARRAY};
}
@Override
public Class returnedClass() {
return Integer[].class;
}
@Override
public boolean equals(Object o, Object o1) throws HibernateException {
return false;
}
@Override
public int hashCode(Object o) throws HibernateException {
return 0;
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
throws HibernateException, SQLException {
Array array = rs.getArray(names[0]);
return array != null ? array.getArray() : null;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (value != null && st != null) {
Array array = session.connection().createArrayOf("int", (Integer[])value);
st.setArray(index, array);
} else {
st.setNull(index, sqlTypes()[0]);
}
}
@Override
public Object deepCopy(Object o) throws HibernateException {
return null;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object o) throws HibernateException {
return null;
}
@Override
public Object assemble(Serializable serializable, Object o) throws HibernateException {
return null;
}
@Override
public Object replace(Object o, Object o1, Object o2) throws HibernateException {
return null;
}
更新部分:
@Override
public CompletableFuture<Void> updateContactGroup_1_0(
ContactGroupDTO contactGroupDTO, String groupId, String fleetId) {
var contactGroupEntity =
contactGroupRepository.findContactGroupByGroupAndFleetId(Long.parseLong(groupId), fleetId);
if (contactGroupEntity == null) {
throw new BadRequestException("Group doesn't exist !!");
} else {
return CompletableFuture.supplyAsync(
() -> {
contactGroupRepository.save(
ContactGroupMapper.updateInDB(
contactGroupDTO, groupId, fleetId, contactGroupEntity.getCreatedTime()));
return null;
},
RepositoryUtil.executor());
}
}
【问题讨论】:
-
你能发布最小的、可重现的例子stackoverflow.com/help/minimal-reproducible-example 吗?
-
@MateuszJaszewski 我已经更新了问题
-
你是怎么做数组和实体之间的映射的?
标签: java spring postgresql jpa