开发者

Jpa: where put toString() custom methods?

I have used Netbeans to create automatically jpa entities starting from a db. Now I need to insert some logic code inside these entities. For example, first of all I need to write a custom toString() method for every jpa entity class. The problem is where I have to put that code ? I know that jpa classes could be overwritten by Netbeans when I'll launch again the jpa "wizard" after the next db schema update. So I'd like to write some entity logic without renounce the jpa auto-generation features of Netbeans. Does I need to use an external tools like a merging tools, a preprocessor features or I need to implement some inheritance class or开发者_如何学运维 a specific pattern ? In the past I have used Apache Cayenne. For every db entity it creates two java classes. The first (the parent), with the fields entity mapping, and the second (an empty child class) as a container for the logic, which is never overwritten (and nor regenerated).

Any advices will be appreciated.

Best regards from Italy


An alternative to generating the entity beans from the schema is to allow JPA to create the schema from the entity beans. I've found that it makes updating & maintaining of the DB schema much easier.


I'd suggest you tackle this as a source control problem. Generate your classes, then modify them as you need. Check the results into source control once you're happy. When the database schema changes, regenerate the classes. They will lack your modifications, but this is fine. Now, synchronise your local copy of the code with what's in source control: you will see two kinds of outgoing changes: changes made to reflect the change in the schema, and deletions of your modifications (because they've been blindly overridden). Use your source control tool to throw away the latter kind of changes, and keep the former; essentially, you are merging the new generated version with the old modified version, and keeping the bits you want from both.

I don't use NetBeans, so i can't describe how to do this in detail. In Eclipse, it's straightforward: regenerate, select all, Team > Synchronize, then go through and do 'copy current change from right to left' wherever you need to.


Yes, I could use a revision control system to synchronize the custom source with the auto-generated code. But is it correct to code business logic inside jpa entity class ???

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜