Struts2 xwork Type Conversion with hibernate
What is the best way to convert types in a Struts2 application?
Right now I want to create a CRUD for a certain hibernate entity in my application. Say I wanted to change the Account
that a User
is associated with. I can just pass in the parameter user.account.id
with a specific value, provided that I have all of the proper getters/setters.
This works perfectly fine when creating an object for the first time, where the account would be null. This makes ognl create a new account object, and set the id to what was passed in.
The problem happens when trying to change the encapsulated Account
object. Using the same user.account.id
parameter, ognl interprets this as getUser().getAccount().setId(param)
. Hibernate interprets this as an attempt to change the primary key.
I understand why it does this, I am just wondering if there is better way for handling this case. This is very common in our application, and I don't want to have to keep creating multiple objects and marshaling them over before I save them via h开发者_运维问答ibernate.
Does anyone no a better way to solve this problem in struts2?
Type Converters for Persistence
Create a type converter for the entity and then just pass user.account
, rather than user.account.id
. This will invoke getUser().setAccount(account)
and wont cause you the headaches.
When you update the record, just pass user.account
as a hidden field in the form.
As for a widespread solution for your entities, you have a few options:
Multiple Converters
Create an abstract type converter that handles most of the logic so that you have a subclass-per-entity that is really lightweight. Register each converter in your xwork-conversion.properties
.
Interface-Driven Converter
The approach that I use is that I have an interface called IdBasedJpaEntity
which 99.9% of my entities implement. It defines a getId()
method of type Integer
. I then have a JpaDAORegistry
singleton class that I create when my app starts. I register each of my entities with it and it constructs a single instance of each DAO (basically, a de-facto singleton). I have a map of entity class to DAO instance. This allows my type converter to look up the appropriate DAO instance for any given IdBasedJpaEntity
, allowing me to have a single JpaEntityConverter
class that works with any entity that implements the interface. This route is a little bit more work up front, but has proven highly reusable for me.
精彩评论