Skip to content

Commit

Permalink
added support for AttributeConverter
Browse files Browse the repository at this point in the history
  • Loading branch information
ccleve committed Dec 9, 2019
1 parent 21094a7 commit 0e93567
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ public List<Integer> convertToEntityAttribute(Array dbData) {
if (dbData.getBaseType() != java.sql.Types.INTEGER) {
throw new DbException("Database is not returning an integer array");
}
int[] arr = (int[]) dbData.getArray();

Integer [] arr = (Integer[]) dbData.getArray();
List<Integer> out = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
out.add(arr[i]);
for (Integer i: arr) {
out.add(i);
}
return out;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.dieselpoint.norm.converter;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter
public class StringToIntListConverter implements AttributeConverter<List<Integer>, String> {

@Override
public String convertToDatabaseColumn(List<Integer> attribute) {
if (attribute == null) {
return null;
}
StringBuilder sb = new StringBuilder();
int len = attribute.size();

for (int i = 0; i < len; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(attribute.get(i).intValue());

}
return sb.toString();
}

@Override
public List<Integer> convertToEntityAttribute(String in) {
// deserialize string in the form "123,456" no spaces allowed
List<Integer> list = new ArrayList<>();
if (in == null || in.length() == 0) {
return list;
}

int value = 0;
for (int i = 0; i < in.length(); i++) {
int digit = in.charAt(i) - '0';
if (digit >= 0 && digit <= 9) {
value = (value * 10) + digit;
} else {
// hit a comma
list.add(value);
value = 0;
}
}
list.add(value);
return list;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -234,9 +234,9 @@ public Object getValue(Object pojo, String name) {
if (value != null) {
if (prop.serializer != null) {
value = prop.serializer.serialize(value);

// TODO put prop.converter here

} else if (prop.converter != null) {
value = prop.converter.convertToDatabaseColumn(value);

} else if (prop.isEnumField) {
// handle enums according to selected enum type
Expand Down Expand Up @@ -274,6 +274,9 @@ public void putValue(Object pojo, String name, Object value, boolean ignoreIfMis
if (value != null) {
if (prop.serializer != null) {
value = prop.serializer.deserialize((String) value, prop.dataType);

} else if (prop.converter != null) {
value = prop.converter.convertToEntityAttribute(value);

} else if (prop.isEnumField) {
value = getEnumConst(prop.enumClass, prop.enumType, value);
Expand Down

0 comments on commit 0e93567

Please sign in to comment.