Setting Refresh of entity beans in ejb3.0

Hi,
I wonder how you can set the refresh rate of entity beans in the EJB 3.0 model. I want to this to avoid explicit calls to of the refresh method of the entitymanager...

The easiest way to cope with this seems to be to just create a new Collection in the business method that wants to manipulate the collection, based on the collection that the read-only getter delivers, .add/.remove on that collection instead, and then use the set-method to write it back, like this (old code commented out):
contentEJB = contentMasterHome().findByPrimaryKey(contentID);
//themeEJB.getContent().add(contentEJB);
Collection content = new ArrayList(themeEJB.getContent());
content.add(contentEJB);
themeEJB.setContent(content);
The overhead is that a new collection has to be created, populated and written back, and I suppose the sql that actually runs when the set method is called is more heavy, but still it's outweighted by the overall performance gain. I'm writing a small CMS system (ie. re-inventing the wheel), and updates aren't that frequent after all, and it won't handle waste amounts of content anyway.
Jon Martin Solaas

Similar Messages

  • Compund primary key in entity bean

    hi,
    can somebody please explain how to use the compound primary key in entity beans? i have got a database table, the key of which consists of three fields, which I assign as PK when setting up the entity bean. In turn I get a compoundPK class, but without get/set-methods - is it necessary to write own get/set-methods within this class?
    In the bean class itself I get a compundPK-create() method - but what is the use of it? actually, in my findByPK-method I need the PK already.
    Hints appreciated - btw, help.sap.com is not very helpful in this case...
    regards, matthias

    WebLogic Server supports mapping a cmr field to the primary key.

  • Use same transaction in entity-bean and Datasource

    Hello
    I've got following problem. In my stateless container managed transaction Sessionbean i do some inserts and update on my container managed entity bean. In the same transaction I have to read some informations on the database. Some of those informations are already set by the entity bean, but not yet commited. Now I want to read them through a javax.sql.DataSource. But this Datasource doesn't use the same transaction as the session bean.
    Question: Is it possible to let a Datasoucre use the same Transaction as Sessionbean?
    (i work with WSAD 4.0.3)
    Thanks

    Hi,
    You would have to check that you are using an XADataSource instance, instead of a 'regular' DataSource instance (which will not adopt the transaction started by the application server). In particular, the JNDI lookup name of the DataSource should actually point to an instance of XADataSource; a special type for container transactions.
    The administration/deployment tools of the WS will allow you to do that, under Resource Factories or DataSources somewhere.
    Both types look the same towards your application code, so your session bean is probably fine the way it is and does not need rewriting. It is merely in the setup of the WS server that the difference lies.
    Best,
    Guy
    http://www.atomikos.com

  • Wrapping entity bean access inside singletons

    Hi all,
    While developing an application based on EJB, i came across a situation which requires some analysis.
    I have a session bean which acts as a session facade - for a set of related entity beans. Since, i wanted to take out all the finders, removes / creator access from the session bean - I created a singleton utility class - which does all the entity bean access. So, the session bean merely calls various methods in the singleton utility class for entity bean access.
    I'am posting it here to get an opinion from others - whether the use of singleton utility class for accessing entity beans - a right approach ?(even though - it does not create any problems during normal testing..)
    Please comment on this approach..
    Thanks in advance,
    Baskar

    Hi,
    The dictionary bean example was quite useful. Thanks.
    But I'am still confused with one thing. i.e.,
    What would be the difference between the below 2 approaches :
    1. Locating & updating / reading from DB tables through CMPs directly from inside the session bean methods. In which case, each client request will have one instance of session bean activated - to service the request. By this, in each of these different session bean instances, the entity bean instances will be created/found/removed/updated.
    2. Using a singleton class/a class containing static methods inside which entity bean instances will be created/found/removed/updated. These static methods/ singleton methods will be used inside each of the session bean instances - in which case, all session bean instances share the code for entity bean access.
    Please give your comments..

  • Problem with cache refresh entity bean / server node

    Hello,
    ive got a big problem and not found answer in sdn until now.
    Ive got a job that gets data from maxdb by sapjob - jco - session bean - entity bean - database.
    this job works daily. the data to work with is written directly to database from external.
    on first execute it works, but second etc not. i search for answer and i guess something:
    entity bean is cached (increase percormance?) with results of the select and do not know about new database entries when they are written directly to database. so second select says: there is no new data (but they are there).
    i only get this new data when i restart netweaver server node, then it works, but only for one time. then result is in cache and then i have to do same procedure before it goes (restart server).
    how can i get this data? is there any setting for force node to refresh cache? or any other settings to affect something like this?
    we have to go live with this in august.
    thx for help.
    Version: NW04, SP21

    thanks at first.
    OSS was the next step i consider, enforcedly.
    I hoped that there was a kind of timeout in visual admin or somewhere else where (for example) i can set a special time (seconds?) for refreshig the cache. Or i can set a flag for "do not cache entity beans".
    Someone else any idea?
    Nowadays on test system whe have made a task that starts windows every night so that netweaver also is "fresh". a kind of resolution but not the best and no resolution for the productiv system. or whe have to write a kind of batch job that only restarts server node once a day.
    New Info:
    I think cache was filled directly after restart.
    when we restart, then data are written, and then our application wanted to read them, they are also not seen.
    The data are only seen by bean when the restart takes place AFTER the data are written into db.
    So we change restart time to point after data are written. so we will test if this works, on monday we will see.
    Edited by: Torsten on Jul 11, 2008 11:27 AM

  • EJB3 entity bean update, best practice

    I have an ejb3 entity bean that models a time that can be reserved in a booking system.
    I need a way to reserve the time for a specific user. Ofcourse the reservation should not overwrite if the time has already been reserved by another user.
    What is the best/cleaneste way to provide this service?
    I have thought of the following ways.
    I could put a version field on the entity. When the user is set in the frontend the entitybean will check that the time is not already reserved. If not it will be sent backup to the stateless session bean for persisting. If the time has been reserved by another user in the meantime JPA will throw an exception since the version doesn't match any more. The frontend can then show the error to the user.
    I could make the frontend call a method in a stateless session bean to reserve the time. The function could take the times primary id and the users primary id and loaded them from persistence. Then check if the time is already reserver else set the user and persist the time again. This should ofcourse be within a transaction and possibly also use a version attribute on the entity.

    Only fields detected as persistent-dirty will be updated in the database record.
    Laurent

  • Creating entity beans (EJB3) from xml schema

    Dear friends,
    I have a XML schema.. and I want to implement an Enterprise application with EJB3 Entity Beans exposed through a set of JAX-WS Web-Services...
    question: how to define the entities from the XML schema?

    Two alternatives:
    1) JAXB 2.0 generates POJOs with JAXB annotations in them. You can take ownership of those POJOs and add Java Persistence API annotations in them by hand. Basically, you will end up having both both JPA and JAXB annotations in the same Java class. You can then use them in your code both with JAXB APIs and JPA APIs.
    2) Have a look at http://hyperjaxb3.dev.java.net/ It is trying to automate what I described in #1. The project is still not complete, so right now, you may have to hand code the JPA annotations.
    Sahoo

  • How set diff. timeouts for entity beans?

    How do i set diff. timeouts for diff. entity beans? Is it in the ejb-jar.xml file? Is this refreshed every time it is accesses?

    Hi there,
    Although not familiar with all of the App servers on the market, I'd say that you are unlikely to find a timeout value for Entity Beans. Passivation of Entity beans is normally a function of the commit options supported by a specific App server. For example, with Commit Option C an entity bean instance should always be returned to the instance pool after a transaction has completed. You can find details of the various commit options in the EJB specification which you can view or download from:
    http://java.sun.com/products/ejb/docs.html
    Hope this helps
    Amanda
    Developer Technical Support
    Sun Microsystems
    http://www.sun.com/developers

  • Error when deploying a simple Entity bean (EJB3) on Glassfich or Sun AS

    Hi,
    After some problems when deploying complex EJB3 Entity bean on GlassFich with a MySQL connector, I have made a simple entity.
    (test with Glassfish and Sun AS with same result)
    With netbean 5.5 => New EJB Module
    File->New->Persistence Unit (and use default values)
    Persistence.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence">
      <persistence-unit name="test" transaction-type="JTA">
       <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
        <jta-data-source>jdbc/sample</jta-data-source>
        <properties>
          <property name="toplink.ddl-generation" value="create-tables"/>
        </properties>
      </persistence-unit>
    </persistence>File->New->Entity Class
    EntityTest.java
    package test;
    import java.io.Serializable;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    @Entity
    public class EntityTest implements Serializable
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        /** Creates a new instance of EntityTest */
        public EntityTest()
        public Long getId()
            return id;
        public void setId(Long id)
            this.id = id;
        public String toString()
            //TODO change toString() implementation to return a better display name
            return "" + this.id;
    }Build of project work fine but when I try to deploy (with the 2 servers), I have the error :
    Exception occured in J2EEC Phase
    com.sun.enterprise.deployment.backend.IASDeploymentException: Deployment Error -- null
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:790)
    at java.util.HashMap$KeyIterator.next(HashMap.java:823)
    at com.sun.enterprise.deployment.backend.EjbModuleDeployer.generatePolicy(EjbModuleDeployer.java:203)
    at com.sun.enterprise.deployment.backend.ModuleDeployer.doRequestFinish(ModuleDeployer.java:171)
    at com.sun.enterprise.deployment.phasing.J2EECPhase.runPhase(J2EECPhase.java:169)
    at com.sun.enterprise.deployment.phasing.DeploymentPhase.executePhase(DeploymentPhase.java:95)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.executePhases(PEDeploymentService.java:871)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:266)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:739)
    at com.sun.enterprise.management.deploy.DeployThread.deploy(DeployThread.java:174)
    at com.sun.enterprise.management.deploy.DeployThread.run(DeployThread.java:210)

    Yes, the problem is that the ejb-jar must contain at least one ejb component. It's a common misconception that Java Persistence API Entity classes are ejb components but they are NOT. The Java Persistence API was developed within the EJB 3.0 JSR and works very well with EJB but the entity classes themselves are not full-fledged ejb components.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Setting composite key in Container Managed Entity Bean

    In my database table i set primary key to two columns making them as composite key. how do i set that in my container managed entity bean home interface findByPrimaryKey() method and in deployment descriptor file.

    1. create another class (say CompositePK) that will embed the two fields keyA and keyB corresponding to the two pk of your table (declare them public) .
    2. in your Bean declare keyA and keyB public.
    3. in the dd declare your bean primary-key-class as CompositePK and the primary-key-field as keyA and keyB.
    this is the method i use (with BAS) even if the key is simple (such as Integer).

  • [EJB3 - ADF Faces] entity bean design

    Hello,
    I have an existant application that use database view (very complex) to retrieve and display values from some tables.
    I have to reproduce the same thing with EJB3 ans ADF Faces in a web application.
    What is for you the best way to design entities beans ?
    1. Create some buisness objects (entity beans) and feed them with a query thru the database view ?
    2. Create a unique entity bean with only attributes who are used by the db view ?
    In this case, the entity bean will be used only for this query.
    3. ?
    I think the best solution is the first one.
    But in this case, how to display the result of the query in an ADF Faces table?
    With the 2nd solution the query returns a list of object which will be used by the adf table. That would be much easier.
    Thanks for your help.

    The popup dialog is used for looking up a value of fields on the form. I have fields "location id" and "sub location id", the popup has cascading drop down lists where I choose which ones I want, then return those values from the popup and display the selection in readonly text inputs. Other inputs also exist on the form. Together they all make the input parameters to the session facade's query.

  • Ejb3 entity bean not generating valid sql for postgres 8.1

    Hello,
    I originally posted this on the jboss seam board as I ran across this error on a seam test example, but it seems it's more generally applicable to ejb3 entity beans not generating sql that postgres can understand. I'll post my message below, all replies are appreciated.
    I'm going through the hello world example from the seam book, and I'm getting an error I cannot resolve, that with an auto generated sql statement, that's not valid for postgres 8.1, the database I'm on. Here's my error:
    17:40:31,370 INFO [STDOUT] Hibernate: select next value for person_id_seq from dual_person_id_seq
    17:40:31,394 WARN [JDBCExceptionReporter] SQL Error: 0, SQLState: 42601
    17:40:31,394 ERROR [JDBCExceptionReporter] ERROR: syntax error at or near "value"
    17:40:31,396 FATAL [application] javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not get next sequence value
    javax.faces.el.EvaluationException: javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not get next sequence value
    Here's the table definition
    - create table Person (id bigint not null, name varchar(255), primary key (id))
    - create table dual_person_id_seq (zero integer)
    - create sequence person_id_seq start with 1 increment by 1
    and here's the entity bean:
    @Entity
    @Name("person")
    @Table(name="person")
    @SequenceGenerator(name="person_sequence", sequenceName="person_id_seq")
    public class Person implements Serializable {
    private long id;
    private String name;
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="person_sequence")
    public long getId() { return id;}
    public void setId(long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    How do I get it to generate a valid sql statement for postgres?

    I think you should try putting the sequence generator annotation over the primary key field. Try it and be sure it works.
    regards,
    Michael

  • Will updates to an EJB3 entity bean update ONLY changed columns?

    Hello,
    If you have an EJB3 entity bean that maps to a table, and then you change the value of ONE of the fields in the entity bean, will each column in the row be updated, OR just the column that changed in the row?
    Thanks

    Only fields detected as persistent-dirty will be updated in the database record.
    Laurent

  • [HOWTO] JSF + Session Facade + Entity Bean (EJB3)

    I'm trying to find a tutorial that shows the advisable way to use JSF with EJB 3 entity beans using the Session Facade pattern (?), but the only tutorials around show very basic usage of JSF (validation, conversions etc.).
    The only thing that is close is this: http://forum.java.sun.com/thread.jspa?threadID=5122284 but still not what I'm looking for.
    Is there any documentation available out there..?
    Message was edited by:
    HakelRausd

    Hi,
    I updated the online doc in blueprints solutions catalog with a small explanation of using JSF with EJB Session Bean at https://blueprints.dev.java.net/bpcatalog/ee5/persistence/ejbfacade.html
    I will add an image soon too. The basic idea for JSF and EJB3 programming model is
    JSF Page --> JSF Managed Bean(backing bean) --> Session Bean --> Java Persistence Object.
    In general, ther would be several JSF pages,and several JSF Managed Beans, and several Java Persistence Objects, but fewer Session Beans. The Session Bean would be expected to be shared and accessed by several managed beans with with Session Bean serving as a facade to the Java Persistence Objects, so there would be few Session Beans.
    The Session Bean would usually be a local Session bean and would only be remote if-and-only-if you wanted RMI-IIOP access. Usually web components like Servlets and JSF Managed Beans use local access to the Session Beans and the access is within the same VM, no remoteness.
    Most of the time, the Session Bean would be a Stateless Session Bean, and would not be a Stateful Session Bean.
    hth,
    Sean

  • EJB3.0 simple entity bean for customer example...

    Can anyone provide a simple step by step instruction on how to start my application of a customer entity bean. like i could add / delete an entry to mySQL DB, i will use Sun as my appserver. im a newbie to ejb. i want to start with that CUSTOMER bean can anybody help pls ? thx! tata-yang

    hello batzee i already have my appserver running
    and found out that he place my EJBSample under Enterprise Application.
    and with these modules inside:
    -EJBsampleSun-ejb.jar      EJBModule      
    -EJBsampleSun-war.war WebModule
    my appserver has:
    EJBsampleSun      true      ${com.sun.aas.instanceRoot}/applications/j2ee-apps/EJBsampleSun      Redeploy
    inside my application:
    1. ejbsamplesun-ejb/src/conf/persistence.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
    <persistence-unit name="EJBsampleSun-ejbPU" transaction-type="JTA">
    <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
    <jta-data-source>jdbc/mySample_dbo</jta-data-source> //question: i have db in mysql named mySample_dbo with customer as my table did i declare it right?
    <properties>
    </properties>
    </persistence-unit>
    </persistence>
    ================
    2. ejbsamplesun-ejb/src/java/ph/icomm/customer.class
    package myejb.ph;
    import java.io.Serializable;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.*;
    @Entity
    @Table(name="Customer")
    public class Customer implements Serializable {
    private int id;
    private String name;
    private String email;
    private String phone;
    @Id
    @Column(name="ID")
    public int getId() {
    return id;
    public void setId(int pk) {
    id = pk;
    @Column(name="Name")
    public String getName() {
    return name;
    public void setName(String n) {
    name = n;
    @Column(name="Email")
    public String getEmail() {
    return email;
    public void setEmail(String e) {
    email = e;
    @Column(name="Phone")
    public String getPhone() {
    return phone;
    public void setPhone(String p) {
    name = p;
    ================
    3. ejbsamplesun-war/src/java/web/postcustomer.class
    // and here is my servlet
    //simply trying to fetch the data in my customer table with ID = 11
    package web;
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import ph.icomm.Customer;
    import web.PostCustomer;
    public class PostCustomer extends HttpServlet {
    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    /* TODO output your page here*/
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet PostCustomer</title>");
    out.println("</head>");
    out.println("<body>");
    try {
    Customer pCustomer = new Customer();
    pCustomer.setId(new Integer("11"));
    out.println("Customer Name is"+pCustomer.getName());
    out.println("<br>");
    out.println("Customer Id is:"+pCustomer.getId());
    out.println("<br>");
    out.println("Customer Email is:"+pCustomer.getEmail());
    out.println("<br>");
    out.println("Customer Phone is:"+pCustomer.getPhone());
    } catch(Exception e) {
    System.out.println("I am inside Exception");
    out.println("<h1>Servlet PostCustomer at " + request.getContextPath() + "</h1>");
    out.println("</body>");
    out.println("</html>");
    out.close();
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    /** Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    // </editor-fold>
    Now, is this complete ejb3.0 already? coz if ill try to RUN this project it give this error:
    Deploying application in domain failed; Deployment Error -- null
    C:\Inetpub\wwwroot\myfolder\_Project\EJBsampleSun\EJBsampleSun-ejb\nbproject\build-impl.xml:312: Deployment error:
    The module has not been deployed.
    See the server log for details.
    BUILD FAILED (total time: 1 second)
    This is quite a long post but have to make sure ill get your kind help and assistance. Thanks!
    tata-yang

Maybe you are looking for