Map some boolean properties as enum Set in Hibernate - java

I have an entity which has some BIT fields into the database:
editable
needs_review
active
These fields are mapped against boolean fields in its Java class using Hibernate 3.6.9 version. That forces me to write an interface method for each List of entities I want to get:
List<Entity> listEditables();
List<Entity> listReviewNeeded();
List<Entity> listActives();
Or write a general interface method to achieve a combination of them:
List<Entity> listEntities(boolean editables, boolean reviewNeeded, boolean actives);
That second choice looks greater, but if I add another field in the future there will be a need to modify the interface itself (and every line of code coupled to it).
So I decided I can express it as an enumeration Set:
public enum EntityType{
EDITABLE, REVIEW_NEEDED, ACTIVE
}
//That way there's no need to change interface method's signature
List<Entity> listEntities(Set<EntityType> requiredTypes);
It makes sense that being an enumeration match what I want to achieve, the Entity type itself should have its own Set<EntityType>:
public class Entity{
Set<EntityType> entityTypes;
}
However instead of that I have the mapped booleans which logically match that Set. Then my question, is there any way to map Set<EntityType> entityTypes in hibernate based in that BIT fields or do I have to manage that logic myself having them as boolean?
UPDATE
Having them mapped as a Set implies the possibility of querying for a List using an in clause, if not it would imply an extra step for conversion between my controller and model codes.
Set<EntityType> typesSet = Sets.newHashSet(EntityType.EDITABLE, EntityType.REVIEW_NEEDED);
//Obtains a list of every single entity which is EDITABLE or REVIEW_NEEDED
session.createCriteria(Entity.class).addRestriction(Restrictions.in("entityTypes",typeSet)).list();

I think I have a solution for you. What you are interested in is a CompositeUserType.
As an example lets use a InetAddress composite user type I wrote lately to map a 128bit IPv6 Address / IPv4Address object to two 64bit long properties inside a user account entity.
The signupIp:InetAddress is mapped towards two columns (there is no column count limit or alike) using:
#Columns(columns = {#Column(name = "ip_low", nullable = true), #Column(name = "ip_high", nullable = true)})
private InetAddress signupIp;
And the interesting part of the implementation looks like this:
public class InetAddressUserType implements CompositeUserType {
#Override
public String[] getPropertyNames() {
return new String [] {"ipLow", "ipHigh"};
}
#Override
public Type[] getPropertyTypes() {
return new Type [] { LongType.INSTANCE, LongType.INSTANCE};
}
#Override
public Object getPropertyValue(Object component, int property) throws HibernateException {
if(component != null)
return toLong((InetAddress)component)[property];
else
return null;
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session) throws HibernateException, SQLException {
if(value != null) {
long [] longs = toLong((InetAddress)value);
st.setLong(index, longs[0]);
st.setLong(index + 1, longs[1]);
}
else {
st.setNull(index, LongType.INSTANCE.sqlType());
st.setNull(index + 1, LongType.INSTANCE.sqlType());
}
}
#Override
public void setPropertyValue(Object component, int property, Object value)
throws HibernateException {
throw new RuntimeException("This object is immutable");
}
#Override
public Class<?> returnedClass() {
return InetAddress.class;
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
return x != null ? x.equals(y) : null == y;
}
#Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names,
SessionImplementor session, Object owner)
throws HibernateException, SQLException {
Long ipLow = rs.getLong(names[0]);
if(!rs.wasNull()) {
Long ipHigh = rs.getLong(names[1]);
try {
return fromLong(new long [] {ipLow, ipHigh});
} catch (UnknownHostException e) {
throw new HibernateException("Failed to get InetAddress: ip = " + ipHigh + " + " + ipLow, e);
}
}
else
return null;
}
#Override
public Object deepCopy(Object value) throws HibernateException {
if(value != null)
try {
return InetAddress.getByAddress(((InetAddress)value).getAddress());
} catch (UnknownHostException e) {
throw new RuntimeException("Impossible Exception: " + e.getMessage(), e);
}
else
return null;
}
#Override
public boolean isMutable() {
return false;
}
...
}
Note that I flexibly switch between Inet4Address and Inet6Address instances depending on the values of ipLow and ipHigh. The composite is marked as immutable and you need to check the documentation and the examples in the Hibernate source code (build in composite user types).
In a similar way you can map your meaningful bit properties. You can query those bits by using a single Restriction.eq refering to your EnumType. You can use the equals method to check the properties object. And if you need to refer to a special mapped bit you can use the dot notation like in signupIp.ipLow to refer to the ipLow property/column.
I guess this is what you are looking for.
Update:
In the end it boils down to define the right order of your properties. Hibernate will always use integer index values to access each property:
//immutable for simplicity
class Status {
private final boolean editable;
private final boolean needsReview;
private final boolean active;
//... constructor + isEditable etc..
}
In your StatusCompositeType class:
public String[] getPropertyNames() {
return new String [] {"editable", "needsReview", "active"};
}
public Type[] getPropertyTypes() {
return new Type [] { BooleanType.INSTANCE, LongType.INSTANCE};
}
public Object getPropertyValue(Object component, int property) throws HibernateException {
if(component != null) {
Status status = (Status)component;
switch(property) {
case 1: return status.isEditable();
case 2: return status.isReviewNeeded();
case 3: return status.isActive();
default: throw new IllegalArgumentException();
}
}
else
return null; //all columns can be set to null if you allow a entity to have a null status.
}
public void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session) throws HibernateException, SQLException {
if(value != null) {
Status status = (Status)value;
st.setBoolean(index, status.isEditable());
st.setBoolean(index + 1, status.isReviewNeeded());
st.setBoolean(index + 2, status.isActive());
}
else {
st.setNull(index, BooleanType.INSTANCE.sqlType());
st.setNull(index + 1, BooleanType.INSTANCE.sqlType());
st.setNull(index + 2, BooleanType.INSTANCE.sqlType());
}
}
public Object nullSafeGet(ResultSet rs, String[] names,
SessionImplementor session, Object owner)
throws HibernateException, SQLException {
Boolean isEditable = rs.getBoolean(names[0]);
if(!rs.wasNull()) {
Boolean isReviewNeeded = rs.getBoolean(names[1]);
Boolean isActive = rs.getBoolean(names[2]);
return new Status(isEditable, isReviewNeeded, isActive);
}
else
return null;
}
The rest is straight forward. Remember to implement equals and hashcode for the user type and add the type to the configuration before you create your sessionFactory.
Once you have everything in place you can create a criteria search and use:
//search for any elements that have a status of editable, no reviewNeeded and is not active (true false false).
criteria.add(Restrictions.eq("status", new Status(true, false, false));
Now your listEntities method may become either: listEntities(Status status) or listEntities(boolean editable, boolean reviewNeeded, boolean isActive).
If you need additional information just check the CompositeType and BasicType implementations Hibernate provides within its own sourcecode (look for implementors of CompositeType and BasicType). Understanding those helps alot to use and learn this intermediate level knowledge of Hibernate.

After some brainstorming, I've gone to a workaround which I consider the second best one being imposible to map an enum for the booleans in Hibernate. This is how I have my Entity class looks now:
public class Entity{
private boolean editable;
private boolean needsReview;
private boolean active;
//getters and setters
}
My listing method is implemented as this:
public List<Entity> listEntities(Set<EntityType> requiredTypes){
Criteria cri = session.createCriteria(Entity.class);
if (requiredTypes.contains(EntityType.EDITABLE)){
cri.addRestriction(Restrictions.eq("editable",true));
}
if (requiredTypes.contains(EntityType.NEEDS_REVIEW)){
cri.addRestriction(Restrictions.eq("needsReview",true));
}
if (requiredTypes.contains(EntityType.ACTIVE)){
cri.addRestriction(Restrictions.eq("active",true));
}
return cri.list();
}
Not bad, but don't know if it's the only way to go with that!

I don't think hibernate provides a way to manage the mappings the way you're describing. You can create your own UserType (https://community.jboss.org/wiki/Java5EnumUserType) but every time you add a new enum value you will have to change the logic in the UserType to map the new field as well.
The alternative will be to convert this into a one to many relationship. Your point is basically that if you want to add more fields you will have to change the signature of listEntities but also you will have to modify your table.
So, instead you can create a table that will contain your entity types and have a #OneToMany` relationship to it from your entity. For example:
Define your flags as required:
public enum Flags {
EDITABLE, REVIEW_NEEDED, ACTIVE
}
Create a one-to-many relationship to EntityType:
#Entity
#Table( name="entity" )
public class Entity implements Serializable {
#OneToMany(mappedBy = "entity")
public Set<EntityType> getEntityTypes() {
return entityTypes;
}
And a many-to-one to Entity:
#Entity
#Table( name="entityType" )
public class EntityType implements Serializable {
#Id
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ENTITY_ID")
private Entity entity;
#Enumerated(EnumType.STRING)
private Flag entityType;
...
}
PD: Please note the code is just an example and is not complete or tested.

Related

Jdbi and Inheritance: Conditional Mapping?

I have a single table called Tags that stores a "Tag" as a row, regardless of what specific subclass they represent. Some rows represent modbus tags, some snmp, some other protocols. All classes inheriting from Tag store their data in this one table, and unused columns simply contain null values.
At the moment, I have DAO methods like, getAllModBusTags() which contains an instruction mapToBean(ModBusTag.class). Eventually all of the subclasses of Tag are fetched from the database (one fetch per protocol) and then added to an ArrayList of the supertype Tag.
My question is, is there a simple means with Jdbi to perform conditional mapping of rows so that if a row contains a specific value, it is mapped to ModBusTag.class but if a row contains a different value it is mapped to SNMPTag.class, and so on and so forth?
My end goal is to have a single select statement that fetches every tag from the database, automaps to the correct bean on a row by row basis and then stores all of these subclass beans in a List of the supertype Tag.
Example Method for Single Type:
#Override
public List<SNMPTag> getSNMPTags(){
try(Handle handle = daoFactory.getDataSourceController().open()) {
return handle.createQuery("SELECT * FROM dbo.Tags WHERE Active = 1 AND Protocol = 'SNMP'")
.mapToBean(SNMPTag.class)
.list();
}
catch(Exception e){
if(sysconfig.getVerbose()){ e.printStackTrace(); }
}
return null;
}
Some bad pseudocode to indicate what I want to do:
#Override
public List<Tag> getAllTags(){
try(Handle handle = daoFactory.getDataSourceController().open()) {
return handle.createQuery("SELECT * FROM dbo.Tags WHERE Active = 1")
.mapRows(row -> row.Protocol.equals("SNMP").mapToBean(SNMPTag.class)
.mapRows(row -> row.Protocol.equals("ModBus").mapToBean(ModBusTag.class)
//etc
.list();
}
catch(Exception e){
if(sysconfig.getVerbose()){ e.printStackTrace(); }
}
return null;
}
You can use RowMapper with some amount of custom code to achieve what you need, we successfully use such approach in our project. Here is simplified general example of this technique:
public class PolymorphicRowMapper implements RowMapper<Parent> {
#Override
public Parent map(ResultSet rs, StatementContext ctx) throws SQLException {
Type type = Type.valueOf(rs.getString("type"));
if (type == Type.A) {
return mapTo(rs, ctx, ChildA.class);
} else if (type == Type.B) {
return mapTo(rs, ctx, ChildB.class);
}
throw new IllegalStateException("Could not resolve mapping strategy for object");
}
private static <T extends Parent> T mapTo(
ResultSet rs,
StatementContext ctx,
Class<T> targetClass
) throws SQLException {
return ctx.getConfig().get(Mappers.class)
.findFor(targetClass)
.orElseThrow(() ->
new NoSuchMapperException(String.format("No mapper registered for %s class", targetClass))
)
.map(rs, ctx);
}
}
public static void main(String[] args) {
var jdbi = Jdbi.create("...")
.registerRowMapper(BeanMapper.factory(ChildA.class))
.registerRowMapper(BeanMapper.factory(ChildB.class));
try (Handle handle = jdbi.open()) {
handle.createQuery("SELECT * FROM table")
.map(new PolymorphicRowMapper());
}
}
public enum Type {
A, B
}
public abstract class Parent {
final Type type;
protected Parent(final Type type) {
this.type = type;
}
}
public class ChildA extends Parent {
public ChildA() {
super(Type.A);
}
}
public class ChildB extends Parent {
public ChildB() {
super(Type.B);
}
}

Access entity id inside Hibernate Usertype

I have created my own hibernate UserType implementation class and it works as expected.
I have a requirement now where i need to have access to the value of "id" field of a particular entity record (which is generated via sequence) inside my Hibernate UserType implementation class. Is it possible to achieve this?
Below is my UserType Implementation:
public class SecureStringType implements UserType {
#Override
public int[] sqlTypes() {
return new int[] { Types.VARCHAR };
}
#Override
public Class returnedClass() {
return SecureString.class;
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
throws SQLException {
String encryptedValue = rs.getString(names[0]);
getDataSecurityService().getActualValue(encryptedValue);
SecureString secureString = new SecureString();
secureString.setActualValue(decryptedValue);
return secureString;
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
} else {
SecureString actualValue = (SecureString) value;
st.setString(index, getDataSecurityService().encrypt(actualValue ));
}
}
// DeepCopy, disassemble, assemble method implementations
}
I have noticed that SharedSessionContractImplementor has the PersistentContext inside which has list of all entities that are loaded, but I don't have a way to determine for which Entity the UserType is being called.
`session.getPersistenceContext().getEntitiesByKey();` has all the `EntityKey` objects but I need to get the one for which this `UserType` is being called currently.
Any ideas?
I've faced the same problem in my codebase. AFAIK, the only option I could find as of yet is to add an ID field in your SecureString type, set it during #PreUpdate/#PreLoad or other callbacks, or in getters and setters/constructors, or set it using an HibernateInterceptor at whatever lifecycle that suits you. You can then access it in nullSafeSet using value.getId() or something. Its nutty, but it works.

Using MySQL "SET" column with Ebean ORM

I'm trying to recreate one of our web apps using Play 2.0 with Ebean and I've hit a road block. I can't figure out how to map MySQL's SET type to a field in the model. I've gotten ENUM columns working using the #Enumerated(EnumType.STRING) annotation but I can't seem to find any info on SET columns.
The table mimics a crontab:
CREATE TABLE IF NOT EXISTS `schedule` (
`id` int(10) unsigned NOT NULL auto_increment,
`task_id` mediumint(8) unsigned NOT NULL default '0',
`month` set('January','February','March','April','May','June','July','August','September','October','November','December') default NULL,
`mday` set('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','-1','-2','-3','-4','-5','-6','-7','-8','-9','-10') default NULL,
`wday` set('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday') default NULL,
`hour` set('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23') default NULL,
`minute` set('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59') default NULL,
`updated` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `event` (`task_id`)
)
I've now created a UserType and related annotations as suggested by MvG:
#Entity
public class Schedule extends Model {
public enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER };
public enum Weekday { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };
#Id
public Long id;
#ManyToOne(cascade = CascadeType.MERGE)
public Task task;
#Version
public Timestamp updated;
#Type(type="models.EnumSetUserType",parameters=#Parameter(name="enumType",value="models.Schedule$Month"))
#Column(name="month", columnDefinition="SET('JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE','JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER')")
#MonthEnum
public EnumSet<Month> months;
#Type(type="models.IntegerSetUserType")
#IntegerSet(min=-30,max=30)
#Column(name="mday",columnDefinition="SET('1','2','3','4','5','6','7','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','-1','-2','-3','-4','-5','-6','-7','-8','-9')")
public Set<Integer> mdays;
#Type(type="models.EnumSetUserType", parameters = #Parameter(name="enumType", value="models.Schedule$Weekday"))
#Column(name="wday", columnDefinition="SET('MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY')")
#WeekdayEnum
public EnumSet<Weekday> weekdays;
#Type(type="models.IntegerSetUserType")
#IntegerSet(min=0,max=23)
#Column(name="hour",columnDefinition="SET('0','1','2','3','4','5','6','7','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23')")
public Set<Integer> hours;
#Type(type="models.IntegerSetUserType")
#IntegerSet(min=0,max=59)
#Column(name="minute",columnDefinition="SET('00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31','32','33','34','35','36','37','38','39','40','41','42','43','44','45','46','47','48','49','50','51','52','53','54','55','56','57','58','59')")
public Set<Integer> minutes;
public static Finder<Long,Schedule> find = new Finder<Long,Schedule>(Long.class, Schedule.class);
}
EnumSetUserType:
public class EnumSetUserType<E extends Enum<E>> implements UserType, ParameterizedType, Serializable {
private Class<? extends EnumSet> clazz = null;
private Class<E> enum_type = null;
#Override
public void setParameterValues(Properties parameters) {
String enum_class_name = parameters.getProperty("enumType");
try {
enum_type = ReflectHelper.classForName(parameters.getProperty("enumType"), this.getClass()).asSubclass(Enum.class);
//enum_type = (Class<E>) Class.forName(enum_class_name);
//enum_type = (Class<E>) Play.application().classloader().loadClass(enum_class_name);
}
catch (ClassNotFoundException e) {
throw new HibernateException("enum class " + enum_class_name + " not found", e);
}
}
#Override
public Object nullSafeGet(ResultSet rs, String[] column_names, SessionImplementor session, Object owner) throws HibernateException, SQLException {
String value_str = rs.getString(column_names[0]);
System.out.println("getting " + column_names[0] + " using " + getClass());
if (rs.wasNull())
return null;
List<E> enum_values = new ArrayList<E>();
for (String value : value_str.split(","))
enum_values.add(Enum.valueOf(enum_type, value));
return EnumSet.copyOf(enum_values);
}
#Override
public void nullSafeSet(PreparedStatement statement, Object object, int index, SessionImplementor session) throws HibernateException, SQLException {
System.out.println("Setting " + index + " to " + object + " using " + getClass());
if (object == null) {
statement.setNull(index, Types.VARCHAR);
return;
}
Set<E> values = (Set<E>) object;
StringBuilder sb = new StringBuilder();
for (E value : values)
sb.append(value.name()).append(",");
System.out.println("Setting " + index + " to " + sb.length() + " using " + getClass());
statement.setString(index, sb.substring(0, sb.length() - 1));
}
#Override
public int[] sqlTypes() {
return new int[] { Types.VARCHAR };
}
#Override
public Class returnedClass() {
return clazz;
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
#Override
public boolean isMutable() {
return false;
}
#Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
#Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y)
return true;
if (x == null || y == null)
return false;
return x.equals(y);
}
#Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
}
It no longer reports any errors, but even when I manually populate and save a Schedule in a controller action, the Set fields aren't saved in the database. How can I get Play+Ebean to work with this table?
If you map an ENUM column to a Java Enumeration, you should probably map a SET column to a Java EnumSet. There is at least one question on SF about mapping EnumSet, but the solution there appears to be a separate table, not the mysql SET type.
It also appears that there is no support in hybernate for mysql SET types. Therefore, you'll have to write your own UserType. I'm not sure about the difference, but it seems you could easily make this an EnhancedUserType, which would probably make your implementation more versatile. If your project allows using LGPL-licensed source code, you might use the implementation of EnumType as a template for your own EnumSetType. Adapting that should be easy, particularly as you could throw away all the “save as ordinal” parts of the code.
Once you have your own UserType for EnumSet, you could annotate the corresponding fields with that #Type. Or in the hibernation configuration, if there is such a thing in your setup. There might be even ways to register the type somewhere, to automatically map all EnumSet instances using that type, but I know too little about this whole hibernation stuff to decide whether this is desirable or even possible. I haven't even figured out yet how the #Enumerated annotation maps to the EnumType implementation.
With the right keywords (UserType EnumSet split), one can find some implementations on the web. So you wouldn't even have to write your own code, but could simply include one of these solutions. Some come with a short description about how to use them.

Hibernate Entities from Multiple Databases

Our data model is separated into schemas on two databases. The schemas are used in isolation except for a few single-key relationships that bridge between the two. There are no write transactions that will span both databases.
Similar to this question Doing a join over 2 tables in different databases using Hibernate, we want to use Hibernate to handle joining the entities. We cannot use the database solution (Federated views on DB2).
We have set up Hibernate with two separate database configurations (Doctor and Patient), which works perfectly when using DAOs to explicitly access a particular session.
We want to use Hibernate to automatically retrieve the entity when we call DoctorBO.getExam().getPatient() Where examination contains an id pointing to the Patient table on the other database.
One way I've tried doing this is using a custom UserType:
public class DistributedUserType implements UserType, ParameterizedType
{
public static final String CLASS = "CLASS";
public static final String SESSION = "SESSION";
private Class<? extends DistributedEntity> returnedClass;
private String session;
/** {#inheritDoc} */
#Override
public int[] sqlTypes()
{
// The column will only be the id
return new int[] { java.sql.Types.BIGINT };
}
/** {#inheritDoc} */
#Override
public Class<? extends DistributedEntity> returnedClass()
{
// Set by typedef parameter
return returnedClass;
}
/** {#inheritDoc} */
#Override
public boolean equals(Object x, Object y) throws HibernateException
{
if (x == y)
{
return true;
}
if ((x == null) || (y == null))
{
return false;
}
Long xId = ((DistributedEntity) x).getId();
Long yId = ((DistributedEntity) y).getId();
if (xId.equals(yId))
{
return true;
}
else
{
return false;
}
}
/** {#inheritDoc} */
#Override
public int hashCode(Object x) throws HibernateException
{
assert (x != null);
return x.hashCode();
}
/** {#inheritDoc} */
#Override
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException
{
Long id = rs.getLong(names[0]);
return HibernateUtils.getSession(session).get(returnedClass, id);
}
/** {#inheritDoc} */
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException
{
DistributedEntity de = (DistributedEntity) value;
st.setLong(index, de.getId());
}
/** {#inheritDoc} */
#Override
public Object deepCopy(Object value) throws HibernateException
{
return value;
}
/** {#inheritDoc} */
#Override
public boolean isMutable()
{
return false;
}
/** {#inheritDoc} */
#Override
public Serializable disassemble(Object value) throws HibernateException
{
return (Serializable) value;
}
/** {#inheritDoc} */
#Override
public Object assemble(Serializable cached, Object owner) throws HibernateException
{
return cached;
}
/** {#inheritDoc} */
#Override
public Object replace(Object original, Object target, Object owner) throws HibernateException
{
return original;
}
/** {#inheritDoc} */
#Override
public void setParameterValues(Properties parameters)
{
String clazz = (String) parameters.get(CLASS);
try
{
returnedClass = ReflectHelper.classForName(clazz);
}
catch (ClassNotFoundException e)
{
throw new IllegalArgumentException("Class: " + clazz + " is not a known class type.");
}
session = (String) parameters.get(SESSION);
}
}
Which would then be used:
#TypeDef(name = "testUserType", typeClass = DistributedUserType.class, parameters = {
#Parameter(name = DistributedUserType.CLASS, value = PatientBO.CLASSNAME),
#Parameter(name = DistributedUserType.SESSION, value = HibernateUtils.PATIENT_SESS) })
#Type(type = "testUserType")
#Column(name = "PATIENT_ID")
private PatientBO patient;
The UserType works - the data is loaded correctly with only the Id of the field persisted to the database. I have tested very simple examples of doctor.getExam().getPatient() and doctor.getExam().setPatient() and both seem to work great, however I think this is a terrible hack and I do not have adequate knowledge of Hibernate to know if this is safe to use.
Is there a better way to achieve what we want? Is the way I've described here adequate, or will it cause difficulties in the future?
I don't think it's a good idea. You're trying to make "as if" everything was in a single database, whereas it's not the case. And you make "as if" there was a real toOne association between an exam and a patient, although it's not a real association.
Although you are conscious of this fact, other or future developers won't necessarily be, and will wonder why it's not possible to make a query such as
select e from Exam e left join fetch e.patient
or
select e from Exam e where e.patient.name like 'Smith%'
In short, your pseudo-association only fulfills a very small part of the contract a regular association offers, and this will, IMO, cause more confusion than comfort.
Nothing stops you from having a utility method like
Patient getExamPatient(Exam e)
that does the same thing, but makes it clear that there is no real asociation between both entities.

Trim string field in JPA

I have a db table with column of datatype char(20). I'm not allowed to change it to a varchar.
I'm writing a JPA entity mapped to this table. I would like the string field representing this column in my entity class to always contain the trimmed value, not the 20-character value padded with spaces that exists in the db.
I can't see any easy way to do this. (an annotation would rock!). At the moment I'm just returning a trimmed value from my getter(), but this feels like a kludge.
A google search is offering no help on this. Any ideas?
Or you can use lifecycle annotations:
#Entity
public class MyEntity {
#PostLoad
protected void repair(){
if(myStringProperty!=null)myStringProperty=myStringProperty.trim();
}
private String myStringProperty;
public String getMyStringProperty() {
return myStringProperty;
}
public void setMyStringProperty(String myStringProperty) {
this.myStringProperty = myStringProperty;
}
}
If this occurs on multiple entities you can create a custom annotation and write a dedicated EntityListener.
Annotation
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.FIELD)
public #interface Trim {}
Listener
public class TrimListener {
private final Map<Class<?>, Set<Field>> trimProperties =
new HashMap<Class<?>, Set<Field>>();
#PostLoad
public void repairAfterLoad(final Object entity) throws Exception {
for (final Field fieldToTrim : getTrimProperties(entity.getClass())) {
final String propertyValue = (String) fieldToTrim.get(entity);
if (propertyValue != null)
fieldToTrim.set(entity, propertyValue.trim());
}
}
private Set<Field> getTrimProperties(Class<?> entityClass) throws Exception {
if (Object.class.equals(entityClass))
return Collections.emptySet();
Set<Field> propertiesToTrim = trimProperties.get(entityClass);
if (propertiesToTrim == null) {
propertiesToTrim = new HashSet<Field>();
for (final Field field : entityClass.getDeclaredFields()) {
if (field.getType().equals(String.class)
&& field.getAnnotation(Trim.class) != null) {
field.setAccessible(true);
propertiesToTrim.add(field);
}
}
trimProperties.put(entityClass, propertiesToTrim);
}
return propertiesToTrim;
}
}
Now annotate all relevant String fields with #Trim and register the Listener as default entity listener in your persistence.xml:
<persistence-unit ..>
<!-- ... -->
<default-entity-listeners>
com.somepackage.TrimListener
and.maybe.SomeOtherListener
</default-entity-listeners>
</persistence-unit>
The accepted answer (using JPA entity listeners / #Trim annotation) is a dangerous one. Calling the setter on the retrieved entity appears to mark the entity as dirty. When I tried this myself at a root entity level (using Spring3 / hibernate), it triggered tons of extraneous updates to related entities that were otherwise not modified during the transaction. It was a real mess in production, and tracking it down to this being the cause took time.
In the end I opted to go with the more straightforward approach of trimming each of the fields manually on-demand (in a custom entity-to-domain mapper, or in the entity getter) similar to Edwin's answer.
It's an old question but it was very useful for me to get to my answer. In my case, the easiest way was to create a simple "javax.persistence.Converter", like this:
#Converter
public class StringTrimConverter implements AttributeConverter<String, String> {
#Override
public String convertToDatabaseColumn(String attribute) {
return attribute;
}
#Override
public String convertToEntityAttribute(String dbData) {
return dbData.trim();
}
}
And you can use it like this:
#Entity
#Table(name = "ViewAddress")
public class PostalAddress extends DbObject {
#Convert(converter = StringTrimConverter.class)
private String street;
#Convert(converter = StringTrimConverter.class)
private String number;
(...)
It works just fine.
Put the annotation on the getter method, set the #Acesss to AccessType.Property and trim the field there using String.trim() method.
Or simply put the trim in the getter method and always access the field through it. It is not going to get any simpler than that.
If you do not mind using pure Hibernate and deviating from the JPA standard you can use Hibernate #ColumnTransformer provided that you have a database function to do the work of
You can find how to do it in the Hibernate reference:
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-column-read-and-write
I hope that helps!
I am using this method, which makes the trimming transparent without having to use annotations in every string field.
In the same package that you have your session factory class (the one you use to get Sessions, e.g org.blablabla.yourpackage.etc.SessionGetter.getSession(), you must create a file named package-info.java and put this content inside it:
#TypeDefs({
#TypeDef(name = "trimmedStringType",
defaultForType = String.class,
typeClass = StringUserType.class)
})
package org.blablabla.yourpackage.etc;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
Then you create the class StringUserType in this same package:
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.usertype.EnhancedUserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class StringUserType implements EnhancedUserType, Serializable {
private static final int[] SQL_TYPES = new int[]{Types.VARCHAR};
#Override
public int[] sqlTypes() {
return SQL_TYPES;
}
#Override
public Class returnedClass() {
return String.class;
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y) {
return true;
}
if (x == null || y == null) {
return false;
}
String dtx = (String) x;
String dty = (String) y;
return dtx.equals(dty);
}
#Override
public int hashCode(Object object) throws HibernateException {
return object.hashCode();
}
#Override
public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner)
throws HibernateException, SQLException {
Object s = StandardBasicTypes.STRING.nullSafeGet(resultSet, names, session, owner);
if (s == null) {
return null;
}
return s.toString().trim();
}
#Override
public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index, SessionImplementor session)
throws HibernateException, SQLException {
if (value == null) {
StandardBasicTypes.STRING.nullSafeSet(preparedStatement, null, index, session);
} else {
StandardBasicTypes.STRING.nullSafeSet(preparedStatement, value.toString().trim(), index, session);
}
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
#Override
public boolean isMutable() {
return false;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
#Override
public Object assemble(Serializable cached, Object value) throws HibernateException {
return cached;
}
#Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
#Override
public String objectToSQLString(Object object) {
throw new UnsupportedOperationException();
}
#Override
public String toXMLString(Object object) {
return object.toString();
}
#Override
public Object fromXMLString(String string) {
return string;
}
}
And that's it, no need to create custom annotations in your beans, it will "magically" trim the strings whenever you get the objects from the database.
What JPA provider are you using?
If you are using EclipseLink CHAR fields are trimmed by default. You can disable this through the session trimStrings property (ensure you have not set this).
Accepted answer works except registering the listener in persistence.xml. I did it with orm.xml.
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm
http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd"
version="2.1">
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.example.TrimListener">
</entity-listener>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
All you have to do is put this on your controller and it works as expected you dont need a listener or anything of that
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
If your domain requirement states it needs trimmed information, you need to store the data in trimmed value. I see nothing wrong about it.
Domain Model
An object model of the
domain that incorporates both behavior
and data. (PEAA - Martin Fowler)
If you explicitly have to enforce the business rule at the database level, one option is that you have a choice of writing a trigger, you can use built-in SQL trim method. But it will be like using a rocket to crack an egg.

Categories

Resources