Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving/loading generic java type to postgresql database column

I'm trying to implement some simple auditing functionality for my java app. Here's a snippet of my audit class:

public class Audit<C, T> {
    public final Class<C> modifiedClass;
    public final Date modificationTime;
    public final MyFieldMeta<C, T> fieldMeta; //contains Class<T>
    public final T newValue;

    //constructor, etc...
}

When it comes to persisting these audit objects, I'd prefer to have just one table storing all varieties independent of what T is. I'm using postresql, and I'm wondering what the best approach is for saving newValue to a column, then getting it back again.

newValue is limited to fairly simple types that have postgresql equivalents - String, Integer, Date etc. So storing the value as text and the type as varchar in a separate column, then mapping them back in the java wouldn't be too hard. Is there a slicker approach?

like image 904
Paul Bellora Avatar asked Nov 28 '25 07:11

Paul Bellora


1 Answers

Once you 'flatten' the data types in your database, you will rely on logic to convert it back, which could cause problems. Consider the value: 11.12

Is that text 11.12, as in chapter numbers? Is that 11.12 as in a monetary value? Is that 11th December?

Unless you can guarantee that a value can always be distinctly mapped to a type, the only other way around it is to add an additional type marker to the field, which you must then parse out, for instance: s11.12 to mean "a String of value 11.12".

like image 154
Alan Escreet Avatar answered Nov 29 '25 19:11

Alan Escreet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!