1

I am current porting some legacy code over to using JPA and have run into an issue trying to simplify one of the tables into an entity.

I have a table of various readings taken throughout a 24hr period - every half-hour. It looks like:

Date     |R1|R2|R3...R48

1/1/2012,1,5,1,3,3,4,5,5....etc

I'd like my entity bean to look something like:

@Entity
public class Reading {

    @Id
    String date;

    @??
    int[] values;

    @???
    int sumOfValues
}

Any suggestions how I could approach this? Is it even possible? Also - I only want to read these values, if that make it any easier. I'm using EclipseLink 2.4 with MongoDB

** UPDATE **

Almost have it - but need to maintain order somehow (I think the fields are mapped out of order) - or pass through a reference to the column name:

@Entity  
@Customizer (RawDataCustomizer.class)  
public class Reading {  
private List<Integer> values...  
public void setValue(Integer value)...  
public static class RawDataCustomizer implements DescriptorCustomizer {  

    @Override  
    public void customize(ClassDescriptor descriptor) throws Exception {  
    //loses ordering?  
    for (int i=1; i<=48; i++)  
    descriptor.addDirectMapping("R"+i, "getValue", "setValue", "r"+i);  

}  
Silver
  • 4,911
  • 3
  • 15
  • 16

2 Answers2

0

I don't think you can tell JPA to map to an array out of the box. You would need to map each and every columns and do some custom code to create the array:

  • using @Embedded like in this answer
  • or using a @NamedNativeQuery with the query something like

    SELECT Date, concact(R1,',',R2,',',R3,...) AS R FROM MYTABLE

and in the setter:

public void setR(String r) {
  String[] myarray = r.split(',');
  // Convert String[] to int[] and compute sum
}

Note the second solution is really a workaround. I would privilege mapping all columns and do the computation outside the Entity

Community
  • 1
  • 1
JScoobyCed
  • 10,203
  • 6
  • 34
  • 58
  • I'd prefer something like the @Embedded approach - but really that just gives me a class filled with discrete fields that is still unwieldy to convert to an array. Ideally I'd like `@Embedded R; public static class R { @Collection("rs") private int r1; private int r2... public List getRs(); }` – Silver Nov 15 '12 at 02:46
0

Final solution, using @Customizer - not ideal at all - but works well enough for now:

public static class RawDataMapping extends EISDirectMapping  {
    private final int index;
    public RawDataMapping(int index, String attributeName,String fieldName) {
        super();
        this.index = index;
        setAttributeName(attributeName);
        setFieldName(fieldName);
        setAttributeAccessor(new CustomAccessorAttributeAccessor(this));
    }
    public void set(Object object, Object value)...
    public Object get(Object object)...
}
Silver
  • 4,911
  • 3
  • 15
  • 16