Java/JAXB: Unmarshall Xml to specific subclass based on an attribute

JAXB is a spec, specific implementations will provide extension points to do things such as this. If you are using EclipseLink JAXB (MOXy) you could modify the Shape class as follows: import javax.xml.bind.annotation.XmlAttribute; import org.eclipse.persistence.oxm.annotations.XmlCustomizer; @XmlCustomizer(ShapeCustomizer.class) public abstract class Shape { int points; @XmlAttribute public int getPoints() { return points; } public void setPoints(int points) … Read more

How to use Postgres JSONB datatype with JPA?

All the answers helped me to reach the final solution that is ready for JPA and not EclipseLink or Hibernate specifically. import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import javax.json.Json; import javax.json.JsonObject; import javax.persistence.Converter; import org.postgresql.util.PGobject; @Converter(autoApply = true) public class JsonConverter implements javax.persistence.AttributeConverter<JsonObject, Object> { private static final long serialVersionUID = 1L; private static ObjectMapper … Read more

Manually specify the value of a primary key in JPA @GeneratedValue column

This works with eclipselink. It will create a seperate table for the sequence, but that shouldn’t pose a problem. @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name=”id”, insertable=true, updatable=true, unique=true, nullable=false) private Long id; GenerationType.AUTO will choose the ideal generation strategy. Since the field is specified as insertable and updateable, a TABLE generation strategy will be used. This means eclipselink … Read more

How to silently truncate strings while storing them when they are longer than the column length definition?

One can truncate a string according to the JPA annotations in the setter for the corresponding field: public void setX(String x) { try { int size = getClass().getDeclaredField(“x”).getAnnotation(Column.class).length(); int inLength = x.length(); if (inLength>size) { x = x.substring(0, size); } } catch (NoSuchFieldException ex) { } catch (SecurityException ex) { } this.x = x; } … Read more