How to create a cache for JPA Entities using an EJB

Hello everybody! I have recently got started with JPA 2.0 (I use eclipseLink) and EJB 3.1 and have a problem to figure out how to best implement a cache for my JPA Entities using an EJB.
In the following I try to describe my problem.. I know it is a bit verbose, but hope somebody will help me.. (I highlighted in bold the core of my problem, in case you want to first decide if you can/want help and in the case spend another couple of minutes to understand the domain)
I have the following JPA Entities:
@Entity Genre{
private String name;
@OneToMany(mappedBy = "genre", cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Collection<Novel> novels;
@Entity
class Novel{
@ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Genre genre;
private String titleUnique;
@OneToMany(mappedBy="novel", cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Collection<NovelEdition> editions;
@Entity
class NovelEdition{
private String publisherNameUnique;
private String year;
@ManyToOne(optional=false, cascade={CascadeType.PERSIST, CascadeType.MERGE})
private Novel novel;
@ManyToOne(optional=false, cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Catalog appearsInCatalog;
@Entity
class Catalog{
private String name;
@OneToMany(mappedBy = "appearsInCatalog", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
private Collection<NovelEdition> novelsInCatalog;
The idea is to have several Novels, belonging each to a specific Genre, for which can exist more than an edition (different publisher, year, etc). For semplicity a NovelEdition can belong to just one Catalog, being such a Catalog represented by such a text file:
FILE 1:
Catalog: Name Of Catalog 1
"Title of Novel 1", "Genre1 name","Publisher1 Name", 2009
"Title of Novel 2", "Genre1 name","Pulisher2 Name", 2010
FILE 2:
Catalog: Name Of Catalog 2
"Title of Novel 1", "Genre1 name","Publisher2 Name", 2011
"Title of Novel 2", "Genre1 name","Pulisher1 Name", 2011
Each entity has associated a Stateless EJB that acts as a DAO, using a Transaction Scoped EntityManager. For example:
@Stateless
public class NovelDAO extends AbstractDAO<Novel> {
@PersistenceContext(unitName = "XXX")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
public NovelDAO() {
super(Novel.class);
//NovelDAO Specific methods
I am interested at when the catalog files are parsed and the corresponding entities are built (I usually read a whole batch of Catalogs at a time).
Being the parsing a String-driven procedure, I don't want to repeat actions like novelDAO.getByName("Title of Novel 1") so I would like to use a centralized cache for mappings of type String-Identifier->Entity object.
Currently I use +3 Objects+:
1) The file parser, which does something like:
final CatalogBuilder catalogBuilder = //JNDI Lookup
//for each file:
String catalogName = parseCatalogName(file);
catalogBuilder.setCatalogName(catalogName);
//For each novel edition
String title= parseNovelTitle();
String genre= parseGenre();
catalogBuilder.addNovelEdition(title, genre, publisher, year);
//End foreach
catalogBuilder.build();
2) The CatalogBuilder is a Stateful EJB which uses the Cache and gets re-initialized every time a new Catalog file is parsed and gets "removed" after a catalog is persisted.
@Stateful
public class CatalogBuilder {
@PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
private EntityManager em;
@EJB
private Cache cache;
private Catalog catalog;
@PostConstruct
public void initialize() {
catalog = new Catalog();
catalog.setNovelsInCatalog(new ArrayList<NovelEdition>());
public void addNovelEdition(String title, String genreStr, String publisher, String year){
Genre genre = cache.findGenreCreateIfAbsent(genreStr);//##
Novel novel = cache.findNovelCreateIfAbsent(title, genre);//##
NovelEdition novEd = new NovelEdition();
novEd.setNovel(novel);
//novEd.set publisher year catalog
catalog.getNovelsInCatalog().add();
public void setCatalogName(String name) {
catalog.setName(name);
@Remove
public void build(){
em.merge(catalog);
3) Finally, the problematic bean: Cache. For CatalogBuilder I used an EXTENDED persistence context (which I need as the Parser executes several succesive transactions) together with a Stateful EJB; but in this case I am not really sure what I need. In fact, the cache:
Should stay in memory until the parser is finished with its job, but not longer (should not be a singleton) as the parsing is just a very particular activity which happens rarely.
Should keep all of the entities in context, and should return managed entities form mehtods marked with ##, otherwise the attempt to persist the catalog should fail (duplicated INSERTs)..
Should use the same persistence context as the CatalogBuilder.
What I have now is :
@Stateful
public class Cache {
@PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
private EntityManager em;
@EJB
private sessionbean.GenreDAO genreDAO;
//DAOs for other cached entities
Map<String, Genre> genreName2Object=new TreeMap<String, Genre>();
@PostConstruct
public void initialize(){
for (Genre g: genreDAO.findAll()) {
genreName2Object.put(g.getName(), em.merge(g));
public Genre findGenreCreateIfAbsent(String genreName){
if (genreName2Object.containsKey(genreName){
return genreName2Object.get(genreName);
Genre g = new Genre();
g.setName();
g.setNovels(new ArrayList<Novel>());
genreDAO.persist(t);
genreName2Object.put(t.getIdentifier(), em.merge(t));
return t;
But honestly I couldn't find a solution which satisfies these 3 points at the same time. For example, using another stateful bean with an extended persistence context (PC) would work for the 1st parsed file, but I have no idea what should happen from the 2nd file on.. Indeed, for the 1st file the PC will be created and propagated from CatalogBuilder to Cache, which will then use the same PC. But after build() returns, the PC of CatalogBuilder should (I guess) be removed and re-created during the succesive parsing, although the PC of Cache should stay "alive": shouldn't in this case an exception being thrown? Another problem is what to do when the Cache bean is passivated. Currently I get the exception:
"passivateEJB(), Exception caught ->
java.io.IOException: java.io.IOException
at com.sun.ejb.base.io.IOUtils.serializeObject(IOUtils.java:101)
at com.sun.ejb.containers.util.cache.LruSessionCache.saveStateToStore(LruSessionCache.java:501)"
Hence, I have no Idea how to implement my cache.. Can you please tell me how would you solve the problem?
Many thanks!
Bye

Hi Chris,
thanks for your reply!
I've tried to add the following into persistence.xml (although I've read that eclipseLink uses L2 cache by default..):
<shared-cache-mode>ALL</shared-cache-mode>
Then I replaced the Cache bean with a stateless bean which has methods like
Genre findGenreCreateIfAbsent(String genreName){
Genre genre = genreDAO.findByName(genreName);
if (genre!=null){
return genre;
genre = //Build new genre object
genreDAO.persist(genre);
return genre;
As far as I undestood, the shared cache should automatically store the genre and avoid querying the DB multiple times for the same genre, but unfortunately this is not the case: if I use a FINE logging level, I see really a lot of SELECT queries, which I didn't see with my "home made" Cache...
I am really confused.. :(
Thanks again for helping + bye

Similar Messages

  • How to create an instance for RemoteSession without using create() method

    How to create an instance for RemoteSession without using create() method?

    What's RemoteSession? Not in the JDK. And does the question have anything to do with concurrency?

  • How to create Support function for internal Class use

    I have created a class to find the MoonRise and Set time. There is a java code available and I am translating it to Obj-C.
    My problem is that for the calculation there are many support functions which is internally used. When I try to duplicate this as follows
    -(double) frac:(double)x {
    // returns the fractional part of x as used in minimoon and minisun
    double a;
    a = x - floor(x);
    if (a < 0) a += 1;
    return a;
    -(void)minimoon:(double)t {
    // takes t and returns the geocentric ra and dec in an array mooneq
    // claimed good to 5' (angle) in ra and 1' in dec
    // tallies with another approximate method and with ICE for a couple of dates
    double L0, L, LS, F, D, H, S, N, DL, CB, L_moon, B_moon, V, W, X, Y, Z, RHO;
    //var mooneq = new Array;
    L0 = frac(0.606433 + 1336.855225 * t); // mean longitude of moon
    At this point it gives an error implicit declaration of function frac,
    My question is how to create such helper functions which are used internally, actually there are many such functions where functionA call B which calls C.
    Thanks
    Raj

    Here's yet another approach (creating a private category):
    @interface MYClass (Private)
    - (double)frac:(double)x;
    @end
    @implementation MYClass
    - (void)minimoon:(double)t {
    // takes t and returns the geocentric ra and dec in an array mooneq
    // claimed good to 5' (angle) in ra and 1' in dec
    // tallies with another approximate method and with ICE for a couple of dates
    double L0, L, LS, F, D, H, S, N, DL, CB, L_moon, B_moon, V, W, X, Y, Z, RHO;
    //var mooneq = new Array;
    L0 = [self frac:(0.606433 + 1336.855225 * t)]; // mean longitude of moon
    - (double)frac:(double)x
    // returns the fractional part of x as used in minimoon and minisun
    double a;
    a = x - floor(x);
    if (a < 0) a += 1;
    return a;
    @end
    <div class="jive-quote">rajkhand wrote:
    I liked the first method as I don't have to change much of the java code.
    I like it too. I use that very regularly (though I often use C++/Objective C++), since there is typically a lot of implementation in any class that does not need to be an ObjC instance method. This approach helps to reduce the object's interface to its essentials while keeping maintenance low.
    I'll put all the helper functions above the implementation.
    Is there a good book/web site where I can get such insight? I know C and Delphi/pascal
    Well, Objective-C is a superset of C. If you're porting Java, you'll find protocols (ObjC) similar to interfaces (Java).
    *Getting Started*
    Apple's version of ObjC is different from others. For the language, Apple's docs are the standard (IMO):
    Language:
    http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/ObjC.pdf
    If you are comfortable with C, this guide will help learning Objective-C quickly, though it has not been updated for (Apple's) Objective-C 2.0:
    http://www.amazon.com/Objective-C-Pocket-Reference-Andrew-Duncan/dp/0596004230/r ef=sr14?ie=UTF8&s=books&qid=1245404236&sr=8-4
    There are a few books on the ObjC2 language, but I have not read them (I just read Apple's docs for this).
    OOP/Design:
    http://developer.apple.com/documentation/Cocoa/Conceptual/OOPObjC/OOPObjC.pdf
    Research
    Good site for archives of tips, tricks, and even some hacks:
    http://www.cocoadev.com/
    Apple's lists (Cocoa, Xcode, ObjC, and specific technologies):
    http://lists.apple.com/mailman/listinfo
    This one sees the most traffic for Cocoa, and ObjC topics :
    http://lists.apple.com/mailman/listinfo/cocoa-dev
    Online archive for aforementioned Xcode and Cocoa list submissions:
    http://www.cocoabuilder.com/
    There are a lot of good sites/blogs out there as well.
    Questions
    Apple's lists (linked above) will typically yield good answers in a short time, you can also try here.
    Thanks a million
    Raj
    You're Welcome,
    J

  • How to create a ringtone for the Iphone using phonezoo?

    Hi, I just got the Iphone 4 two days ago. I am used to using Phonezoo.com to create my own ringtones and such, because it just texts the created tone to the cell phone. It won't work when I have the Iphone. How do I save the rington from the message?

    Ask phonezoo.

  • Tutorial or instruction s on how to create an extension for dreamweaver

    Can some body please point me to a tutorial or instructions on how to create an extension for dreamweaver
    I used to create extension for flash few years ago. It was quite straight forward, but not for dreamweaver any help will be appreciated.

    Take a look at:
    Extending Dreamweaver Help - http://help.adobe.com/en_US/Dreamweaver/10.0_Extending/
    API Documentation - http://help.adobe.com/en_US/Dreamweaver/10.0_API_Ref/index.html

  • How to create a macro for a planning type in MC8b transaction

    Hi,
    I am presently working for a product allocation demand, which have a information structiure with characteristic and key field.
    the characteristic are production allocation quantity, incoming order quantity, and open order quantity.
    i have created a planning type in which the data updation takes from the excel file to the planning type in mc95.
    but i need to create a macro for this planning type .
    can any body give the details information how to create a Macro for a planning type.
    Thanks and regards
    GopalKrishna

    Dear Gopal
    May be the link would be helpful to you.
    [Planning Types and Macros|http://help.sap.com/saphelp_46c/helpdata/en/a5/631cc443a211d189410000e829fbbd/frameset.htm]
    Drill down the left tab once you opened the link, for more information.
    Thanks
    G. Lakshmipathi

  • How to create custom infotype for training and event management

    hai freinds can any one tell me how to create custom infotype for training and event managment with following fields
    PS No – PA0000-> PERNR
    Name   - PA0001 -> ENAME
    IS PS.No. – PA0001-> PS no. of Immediate Superior
    IS name PA0001 -> ENAME
    thanx in advance
    afzal

    Hi,
    Your question is not clear for me. Since it is a TEM infotype, it could be a PD infotype.
    If you wish to create a PD infotype, use transaction PPCI to create the infotype.
    But before that you need to create a structure HRInnnn (where nnnn is the infotype number) with all the fields relevant for the infotype.
    If you wish to create a PA infotype, use transaction PM01 to create the infotype.
    But before that you may be required to create a strcuture PSnnnn  (where nnnn is the infotype number) with all the fields relevant for the infotype.
    Regards,
    Srini

  • How to create one TO for multiple TRs

    Dear All,
    how to create one TO for multiple TRs, kindly suggest me
    Regards,
    balu

    As for your question: it is discussed in sAP online help:
    http://help.sap.com/saphelp_erp60_sp/helpdata/en/c6/f841f24afa11d182b90000e829fbfe/frameset.htm
    Sorry I misunderstood your question.
    The above mentioned solution won't create one single TO from multiple TR.
    Edited by: Csaba Szommer on Aug 11, 2010 9:46 AM

  • How to create one checksum for 264 vis

    Hi,
    How to create "one Checksum" for 264 Vis.These 264 Vis are Interlinked if i change code for any .vi the checksum Should be update.This checksum is shown on the main window.
    Regards
    Ravindranath
    Solved!
    Go to Solution.

    Here's a slightly simplified version (saved in 8.6).  There's no need for the Get/Set File Position.  The file position is already being incremented with the read.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    Multiple File MD5 Checksum (Version 8.6).vi ‏23 KB

  • How to create new scope for SharePoint calendar?

    How to create new scope for SharePoint calendar?
    I have a calendar list to which I want to create following scopes-
    Annual View
    Half Year 1 (Jan-June)
    Half Year 2 (Jul-Dec)
    Quarter 1 (Jan-Mar)
    Quarter 2 (Apr-Jun)
    Quarter 3 (Jul-Sep)
    Quarter 4 (Oct-Dec)
    How this can be created. Any help appriciated. Thanks.

    Hi Pratima,
    Can you please see below link and code snippet for how to
     format date in gridview.
    http://www.aspdotnet-suresh.com/2011/05/how-to-set-date-format-in-gridview.html
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title>Gridvew Date format</title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView runat="server" ID="gvdetails" DataSourceID="dsdetails" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false">
    <RowStyle BackColor="#EFF3FB" />
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="White" />
    <Columns>
    <asp:BoundField DataField="Date1" HeaderText="Date1" HtmlEncode="false" DataFormatString="{0:s}" />
    <asp:BoundField DataField="Date2" HeaderText="Date2" HtmlEncode="false" DataFormatString="{0:D}" />
    <asp:BoundField DataField="Date3" HeaderText="Date3" HtmlEncode="false" DataFormatString="{0:m}" />
    <asp:BoundField DataField="Date4" HeaderText="Date4" HtmlEncode="false" DataFormatString="{0:d}" />
    <asp:BoundField DataField="Total" HeaderText="Total" HtmlEncode="false" DataFormatString="{0:C2}" />
    </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="dsdetails" runat="server" SelectCommand="select * from DateFormat" ConnectionString="<%$ConnectionStrings:dbconnection %>"></asp:SqlDataSource>
    </div>
    </form>
    </body>
    </html>
    Hope this will help you.
    Regards
    Soni K

  • How to create a PR for each Maintenance Order

    Dear All,
    Please guide me how to create a PR for each Maintenance Order.
    I test on Ides, I have some Maintenance Orders, all of them require the same stock material. When I run MRP, system always create one PR for all requirements. I don't know how to change.
    Regards,
    QuangDD

    Hi,
    As you planning for Stock Items, by running MRP, system will create single PR only. If it is non stock items, then it would be possible to create different PR based on Orders.
    Regards,
    Maheswaran.

  • How to create t-code for a table and how to create transaction variant???

    Hi,
    I have created a custom table zsark.
    Now my requirement is : I have to create a transaction variant zsark_var for sm30 and table zsark. I have to disable the output of the first screen. I have to assign the transaction variant to the transaction code of table zsark.
    Now,
    1.     how to create transaction code to a table. Can any one give me the 
                    staps??
    2.     how to create transaction variant for the above requirement???
    Thanks & Regards,
    Sarkar

    Hi
    1 Goto SE93 transaction
    2 Choose 5th option Transaction with parameters
    3 Give transaction : SM30, Check Skip Initial Screen Press Enter
    4 Goto Bottom left corner, click F4 select viewname, on right hand side give table name
    5 Press one more time F4, choose update , mark it X on right side.
    6 save the transaction.
    Thanks
    sandeep
    reward if helpful

  • How to create transaction code for a Z-table

    How to create transaction code for a Z-table?
    Se93 --> then which radio button to be selected? and what is the program nam e to  be given

    Hi Sam,
    <b>Procedure to create a TCODE for ZTABLE:</b>
    Create a table maintainance/View for the Z* Table.
    Once you create the view goto SE93>Select Parameter transaction and give the short desc.>
    Give the transaction as SM30(Skip the first screen-optional)>Check all check boxes under GUI support>In the default values(grid)section first row give the VIEWNAME as you created initially and the second row UPDATE as X.
    <u><i>Se93 --> then which radio button to be selected</i></u>
    Select the parameter transaction as a radio button.
    <u><i>what is the program nam e to be given</i></u>
    no need to give any program name. Instead you have to give the transaction code name as SM30.
    Pls mark the helpful answers.
    Thanks
    Eswar

  • How to create transaction code for maintenance view

    hai friends,
    i hope every thing goes good.
    i have doubt, how to create transaction code for maintenance view. I created view for tranperant table and now i want to create transaction code for the view.
    i tried and i donot know the screen number and program name and where can i give the view name.
    if any one know please post in details.
    thanks in advance.

    Hi Elam,
    You need to create a "Parameter Transaction".
    What this means is that you will have a transaction (let's call it "ZMAINT") which calls "SM30" and passes in your table name.
    Go to transaction SE93 and enter your new transaction code. Enter in the Tcode description and choose "Transaction with Parameters" (it shouldbe the last radio button).
    Enter in the default transaction "SM30" and tick the "Skip Initial Screen" check box. Hit Enter.
    Now scroll to the bottom of the screen and you will see a Table Control where you will need to enter in the values to the SM30 selection screen.
    Because you hit ENTER, the program will have loaded in the Selection Screen parameters into it's memory. Hit the drop down for "Name of Screen Field" and select "VIEWNAME" and then enter in your Z Table in the "Value" column.
    Now go to the next line and hit the drop down and select "UPDATE" in the "Name of Screen Field". Enter in a "X" in the value column.
    Now save the transaction and there you have it.
    Hope this helps.
    Cheers,
    Pat.
    PS. Kindly assign Reward Points to the posts you find helpful.

  • How to create a substitute for requester in SRM 7.0

    Hi,
    do you know how to create a substitute for requester?
    we have groups of 2 people and we want that they can see and edit shopping carts one of each other. Do you know how is it possible? it will be necessary for all SCs.
    Thanks.
    Regards,
    Nelson

    You can use the "Team Cart" feature introduced in SRM 7 for your requirement.
    Take a look at this wiki page for more information http://wiki.sdn.sap.com/wiki/display/SRM/Team+purchasing
    Edited by: Jay Yang on Mar 31, 2011 10:47 AM

Maybe you are looking for

  • Macbook Pro Hard disk Makes an annoying sound (buzz) while working but functions properly.

    I've got this Macbook Pro 13 inch 2.4 Intel core i5 processor. After about a year the hard disk without any reason started to make an annoying sound (buzzing) while working that sometimes quiets down but when I move the laptop it starts all over agai

  • How to Debug a BackGround Job

    Hi all,          Can any one tell me how to Debugg a BackGround job in 4.7 version. I used something like JDBG in SM37 but its not working. Is there any process for this....

  • J2I5 Register Extraction

    Dear Friends, Good Morning, I am trying to extract  RG23a registers in t code J2i5 and one error message is appearing as Plant code 3050 doest not exist.This is the same plant for which i am doing extraction.I have checked configuration where excise

  • Error message after sending text message

    I keep getting an error message after I send off a text. It says that the number is invalid and that i have to enter the entire 10 digit number, so at this point i go back to the contact list and ensure that i have the area cose as well. I re-send an

  • Concurrent Managers won't start after changing Apps password

    11.5.10.2 E-Business suite on Windows Server 2003 SP2 Concurrent Managers were working fine after install. I have changed the Apps password using FNDCPASS and have run AutoConfig successfully on both the database and applications tiers. Copncurrent M