Showing posts with label XML Serialization. Show all posts
Showing posts with label XML Serialization. Show all posts

Tuesday, September 25, 2012

Serializing JPA or Hibernate entities over the wire

In my previous post, we discussed about the need to map properties between Hibernate entities and DTOs. This is required, because Hibernate instuments the byte-code of the Java entity classes using tools such as JavaAssist.

Many developers often encounter the LazyInitializationException of Hibernate when you try to use the Hibernate/JPA entities in your webservices stack. To enable you to serialize the same Hibernate entites across the wire as XML, we have 2 options -
  1. Use the entity pruner library - This library essentially removes all the hibernate dependencies from your entity classes by pruning them. Though this library is quite stable, developers should be careful about when to prune and unprune.
  2. Use AutoMapper libraries - Using libraries such as Dozer makes it very easy to copy properties from the domain hibernate entity to a DTO class. For e.g.
PersonDTO cleanPerson = mapper.map(person, PersonDTO.class);

Out of the above 2 approaches, I would recommed to use the second one as it is clean and easy to use. It also enforces clean separation of concerns. A good discussion on StackOverFlow is available here.

Thursday, February 09, 2012

Alternatives to XML Serialization

Today, there are a lot of alternatives for XML serialization of data structures. These data interchange formats are smaller and faster than processing XML.
Most popular are Google Protocol Buffers, Thrift (from FaceBook),  Avro and MessagePack. A good article comparing these alternatives is available here -
http://www.igvita.com/2011/08/01/protocol-buffers-avro-thrift-messagepack/

Wikipedia also has an interesting article comparing various data serialization. 

Friday, May 15, 2009

XML serialization tips in .NET

Today, my team ran across a strange issue. Some of the properties on a .NET class were not getting serialized to XML when used in webservices. There was no error message or any other warning. 
Closer examination revealed that the properties not getting serialized were 'read-only' properties; i.e. they had getters but no setters. The default XML Serializer in .NET calls the property getters/setters and hence if a read-only property is present, then it is not serialized.
Once we added setters to the properties, XML serialization worked fine.

There is another option. We can implement the IXmlSerializable interface and write custom serialization code. But this could be very tedious.