java - Persisting a member variable in JPA, when only the type is important -
problem: how store field when type important.
description: have simplified problem description highlight issue. class dragon
has behavior, roar
, stored member variable. roar
typically has no state , doesn't need saved. however, dragon
needs know specific type of roar
has when recreated.
@entity public class dragon implements serializable { @id @generatedvalue(strategy = generationtype.auto) private long id; private double height; private roar roar; public string roar() { return roar.roar(); } } public interface roar { string roar(); } public class quietroar implements roar { public string roar() { return "grr.."; // in real scenario, lots of logic occurs here. } public class loudroar implements roar { public string roar() { return "ahhhgrrrr"; // more logic here. }
possible solution: make roar
field transient , store additional field of type class
holds class type of roar
field. dragon
class becomes:
@entity public class dragon implements serializable { @id @generatedvalue(strategy = generationtype.auto) private long id; private double height; @transient private roar roar; private class<? extends roar> roartype; public void setroar(roar roar) { this.roar = roar; roartype = roar.getclass(); } public string roar() { if(roar == null) { try { roar = roartype.newinstance(); } catch (instantiationexception | illegalaccessexception ex ) { // oo ohh.. } } return roar.roar(); } }
if using eclipselink can use converter this.
http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_converter.htm#chdehjeb
specifically can use classinstanceconverter store name of class in column.
jpa 2.1 define converter concept.
Comments
Post a Comment