I am updating a table using JPA. Postgres is the DB. There is a field which is of type String[] . While updating through API , other fields are getting updated. but this String[] field is updating to null . I have implemented by taking reference of https://www.baeldung.com/java-hibernate-map-postgresql-array . Any help is appreciated
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;
}
Update Part:
@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());
}
}
CodePudding user response:
You want to map String[] but your CustomStringArrayType maps Integer[]. Look at your code:
@Override
public Class returnedClass() {
return Integer[].class;
}
and:
Array array = session.connection().createArrayOf("int", (Integer[])value);
this should be changed to:
@Override
public Class returnedClass() {
return String[].class;
}
and:
Array array = session.connection().createArrayOf("text", (String[])value);