sixtytrees sixtytrees - 3 months ago 10
SQL Question

How to organize a Java class to store SQL table with a composite key?

An SQL table with a compound primary key stores some data.

ID
,
TYPE
and
PAGE
form a composite key, while VAL1 and VAL2 store values.

enter image description here

I want to create a class that has
String name; String val1; String val2;
, populate instances and do conversion between the SQL table and a collection of instances of the class. What would be a good implementation if such a class? I am choosing between these options:

(1) A
class Page
that extends
abstract class Type
that extends
abstract class ID
, but this seems unnatural.

(2) Concatenate ID, TYPE and PAGE, but then first and second entries will clash. Concatenation with special characters like
12_11_2
would cause troubles with escaping these characters in the strings down the road.

(3) A class with five strings (one per each column) seems unnatural, because then I don't have a unique handle like
String compositeKey;


What is the most efficient way to turn SQL table with a composite key into a collection of instances of a class?

Guy Guy
Answer

Use TreeMap with a class MyKey (string A; String B; String C;) as a key and class MyValue (String D; String E) as the value.