• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Conversion between DB data and java data ?

 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Edvins Reisons
Ranch Hand
Posts: 364
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sol Mayer-Orn
Ranch Hand
Posts: 311
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much
 
James Sutherland
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic