Forums Register Login

Conversion between DB data and java data ?

+Pie Number of slices to send: Send
Hi,

I've just started using JPA, and would appreciate it if anyone could help with the following question:

What is the recommended way to define a conversion rule between my database data, and my Java data ?
For example, say my (badly designed) database stores string values of "YES" and "NO", which I'd like to convert to java boolean :


What is the most recommended way to do the conversion ?
Thanks
[ September 30, 2007: Message edited by: Sol Mayer-Orn ]
+Pie Number of slices to send: Send
Not sure that you can do this directly in JPA. With a bit of flexibility, though, either on the Java side (use an enum) or on the DB side (change the column type to whatever a boolean is persisted to), I think one can move forward here.
+Pie Number of slices to send: Send
Thanks very much
+Pie Number of slices to send: Send
The most portable way to define the conversion is to use property access for the class and define get/set methods that convert the value.

i.e.
public class Subscription {
..
@Transient
public boolean isMonthly() {
return isMonthly;
}
public void setIsMonthly(boolean isMonthly) {
this.isMonthly = isMonthly;
}
@Basic
private String getMonthlyString() {
if (isMonthly() {
return "Yes";
} else {
return "No";
}
}
private String setMonthlyString(String value) {
setIsMonthly(value.eqauls("Yes"));
}
}

However most JPA implementation have extended conversion support. If you are using TopLink (or TopLink Essentials, or EclipseLink) you can use a Converter on your mapping. In TopLink 11g you can use the @ObjectTypeConverter and @Convert annotations for this.

If you are using Hibernate you can use their custom type system and their @Type annotation.
Put a gun against his head, pulled my trigger, now he's dead, that tiny ad sure bled
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1263 times.
Similar Threads
Mapping ENUM('0', '1') or CHAR(0) for Boolean
Spring security: initializing bean after succesful authentication?
"Casting" from a Superclass to a subclass
Lock Manager implementation
object caching
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 08:46:44.