craigmiller160
craigmiller160

Reputation: 6263

Java+Hibernate: Fire property change events when object retrieved from database

So, I'm trying to figure this out here, and I'm wondering if it can't even be done in the first place.

Anyway, so I'm using Hibernate for my ORM mapping. All that works perfectly, it builds my persistent beans perfectly, etc. The one area that's bugging me is this: I have one model that, when it is created, needs to pass its values to the UI. I already have a great system set up using PropertyChangeEvents to accomplish this. All of this model's fields are bound properties, whenever their values are changed, an event is fired and the UI updates. Nice, simple, elegant.

The problem is that when I get this model from the database, with Hibernate, I can't add a PropertyChangeListener to it prior to Hibernate loading the model. This means that when Hibernate sets all the fields, events don't get fired. Not being able to use these PropertyChangeEvents would be a real pain, I would have to write a bunch of other code specifically to bypass the system I have set up for the entire application for this one particular context.

I'm hoping there's a way to be able to listen to the fields getting set as Hibernate creates the model, so that the PropertyChangeEvents can make their way to my UI. If not, the best option I can think of is to create a public method in that particular model to allow for PropertyChangeEvents to be forced out for the various fields even though nothing's changed.

Here's the code that retrieves the object from the database. Thanks in advance.

PS. There's a totally unrelated bug where Hibernate is still executing updates on my database upon VM shutdown even though I don't have my program set up to do a save upon shutdown. But that's something I'll deal with in another question, after I have a chance to look over the Hibernate logs and see if I can find the problem there.

public PortfolioModel getPortfolio(int userid) throws HibernateException{
    SQLPortfolioModel portfolio = null;

    Session session = null;
    try{
        session = factory.openSession();
        session.beginTransaction();
        portfolio = (SQLPortfolioModel) session.createCriteria(SQLPortfolioModel.class)
                        .add(Restrictions.naturalId().set("userID", userid))
                        .setFetchMode("stockList", FetchMode.JOIN)
                        .uniqueResult();

        session.getTransaction().commit();
    }
    finally{
        if(session != null){
            session.close();
        }
    }

    return portfolio;
}

Upvotes: 0

Views: 663

Answers (1)

StanislavL
StanislavL

Reputation: 57381

You can use Entity listeners and Callback methods

For the Entity you can define callback method of the Entity like this

@PostLoad
public void processPOstLoad()

Upvotes: 1

Related Questions