Entity Bean Persisting It's Own State

Is there an advantage to codeing a bean to persists it's own state. I don't write many JavaBeans, and have used the Data Access Object Strategy to handle persistance.
Any suggestions on why or why not to have a bean persist it's own state would be appreciated.

I hope I got your question right cause it seems it can be interpreted in two ways.
My argument is that an object isn't responsible for persisting it's own state.
An object can be persisted in many different ways. Supporting all of these ways would cause the class to explode code size ways. You'd probaply be doing a lot of copy pasting and "discovering" that there is a great reuse potential. Too much for one class to handle. Better leave it to an established framework or code a small framework yourself. The DataAcces Object strategy is a commonly used and well established pattern. If your dao is an interface you can potentially plug-in lots of different persistence schemes.

Similar Messages

  • Container-managed persistence Entity bean

    WE use a container-managed persistence Entity bean. To handle the state synchronization between the object & the database, what must WE do?
    Thanks in Advance

    That's the container's job. You can use the commit option A/B/C to control how the DB and objects are synchronized.
    -Scott
    http://www.swiftradius.com

  • [persistence] all work, but can't persist new entity bean

    Hi,
    I have a FacadeBean which is working fine ... I can contact the BD oracle for retrieving my entity beans, update an entity bean etc...
    BUT... I can't create an entity bean :( I don't understand why!!!
    With the same code, I can create, list, etc... on OC4J and JBoss but the create method won't work with WebLogic :|
    Here is the error present in console:
    <09-mars-2007 15 h 03 min 47 s CET> <Error> <EJB> <BEA-010026> <Exception occurr
    ed during commit of transaction Name=[EJB be.starapic.test.ejb.MyEntityFacadeBea
    n.create(be.starapic.test.ejb.MyEntity)],Xid=BEA1-007A82AF3A953057A4BD(30283302)
    ,Status=Rolled back. [Reason=weblogic.transaction.internal.AppSetRollbackOnlyExc
    eption],numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds since begin=1,seconds
    left=30,XAServerResourceInfo[weblogic.jdbc.wrapper.JTSXAResourceImpl]=(ServerRes
    ourceInfo[weblogic.jdbc.wrapper.JTSXAResourceImpl]=(state=rolledback,assigned=Ad
    minServer),xar=weblogic.jdbc.wrapper.JTSXAResourceImpl@110563c,re-Registered = f
    alse),SCInfo[base_domain+AdminServer]=(state=rolledback),properties=({weblogic.t
    ransaction.name=[EJB be.starapic.test.ejb.MyEntityFacadeBean.create(be.starapic.
    test.ejb.MyEntity)], weblogic.jdbc=t3://192.168.100.188:7001}),OwnerTransactionM
    anager=ServerTM[ServerCoordinatorDescriptor=(CoordinatorURL=AdminServer+192.168.
    100.188:7001+base_domain+t3+, XAResources={weblogic.jdbc.wrapper.JTSXAResourceIm
    pl},NonXAResources={})],CoordinatorURL=AdminServer+192.168.100.188:7001+base_dom
    ain+t3+): weblogic.transaction.RollbackException: Unknown reason
    at weblogic.transaction.internal.TransactionImpl.throwRollbackException(
    TransactionImpl.java:1808)
    at weblogic.transaction.internal.ServerTransactionImpl.internalCommit(Se
    rverTransactionImpl.java:333)
    at weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTran
    sactionImpl.java:227)
    at weblogic.ejb.container.internal.BaseRemoteObject.postInvoke1(BaseRemo
    teObject.java:606)
    at weblogic.ejb.container.internal.BaseRemoteObject.postInvokeTxRetry(Ba
    seRemoteObject.java:426)
    at weblogic.ejb.container.internal.StatefulRemoteObject.postInvokeTxRetr
    y(StatefulRemoteObject.java:100)
    at be.starapic.test.ejb.myentityfacade_opn58i_MyEntityFacadeRemoteImpl.c
    reate(myentityfacade_opn58i_MyEntityFacadeRemoteImpl.java:158)
    at be.starapic.test.ejb.myentityfacade_opn58i_MyEntityFacadeRemoteImpl_C
    BV.create(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(Remote
    BusinessIntfProxy.java:42)
    at $Proxy152.create(Unknown Source)
    at be.starapic.test.web.HelloServlet.doGet(HelloServlet.java:88)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run
    (StubSecurityHelper.java:226)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecuri
    tyHelper.java:124)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.jav
    a:283)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.jav
    a:175)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationActio
    n.run(WebAppServletContext.java:3334)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(Authenticate
    dSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(Unknown Source)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppS
    ervletContext.java:2081)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletC
    ontext.java:1987)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.j
    ava:1359)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)
    .>
    <09-mars-2007 15 h 03 min 47 s CET> <Error> <HTTP> <BEA-101020> <[weblogic.servl
    et.internal.WebAppServletContext@144a314 - appName: 'testDeploy', name: '/testDe
    ploy', context-path: '/testDeploy'] Servlet failed with Exception
    javax.ejb.EJBException: nested exception is: weblogic.transaction.internal.AppSe
    tRollbackOnlyException
    at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(Remote
    BusinessIntfProxy.java:57)
    at $Proxy152.create(Unknown Source)
    at be.starapic.test.web.HelloServlet.doGet(HelloServlet.java:88)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    Truncated. see log file for complete stacktrace
    That say nothing good...
    at $Proxy152.create(Unknown Source) is the problem I think but why ...?
    Here is the entity bean:
    @Entity
    @Table(name="table_myentity")
    public class MyEntity implements Serializable
    private static final long serialVersionUID = -5806278646729410835L;
    private int id;
    private String name;
    private int number;
    public void setName(String name) {
    this.name = name;
    public String getName() {
    return name;
    public void setNumber(int number) {
    this.number = number;
    @Column(name="mynumber")
    public int getNumber() {
    return number;
    public void setId(int id) {
    this.id = id;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public int getId() {
    return id;
    May be a problem of auto-generate for the ID...
    Here is the facade bean:
    @Stateful(name="myentityfacade", mappedName="myentityfacade")
    @Remote(MyEntityFacadeRemote.class)
    @Local(MyEntityFacadeLocal.class)
    public class MyEntityFacadeBean implements MyEntityFacadeRemote, MyEntityFacadeLocal {
    @PersistenceContext
    private EntityManager em;
    public MyEntity create(MyEntity meb) {
    em.persist(meb);
    return meb;
    public void update(MyEntity meb) throws IllegalAccessException {
    if (null == em.find(MyEntity.class, meb.getId())) {
    throw new IllegalAccessException("Attempt to update a non existing entity");
    em.merge(meb);
    public void delete(int id) {
    MyEntity meb = em.find(MyEntity.class, id);
    em.remove(meb);
    public void delete(MyEntity meb) {
    meb = em.merge(meb);
    em.remove(meb);
    public MyEntity findById(int id) {
    return em.find(MyEntity.class, id);
    public List<MyEntity> listAll() {
    return em.createQuery("SELECT o FROM MyEntity AS o").getResultList(); //TOPLINK, HIBERNATE
    public List<MyEntity> listFiltered(String filter) {
    return em.createQuery("SELECT o FROM MyEntity AS o "+filter).getResultList(); //TOPLINK, HIBERNATE
    public int getNbMyEntityBean() {
    return this.listAll().size();
    Sorry for the long post... And finnaly here is the code present in the servlet:
    // CREATE
    MyEntity meb1 = new MyEntity();
    meb1.setName("bbb");
    meb1.setNumber(2);
    meb1 = remoteMyEntityFacade.create(meb1);
    Note that the remoteMyEntityFacade is working, because I can call any other buisness method without crashing the application.. Just the create can't work and so, persistence can't be used :(
    Any suggestions ?

    There is a problem with generated key
    that code won't work:
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public int getId() {
    return id;
    But, if I remove line "GeneratedValue", it can insert into the BD, once only :s
    The ID is set to 0 by default, so I can't add more than one entity :s

  • Entity beans caching non-persistent data between transactions

    Some of the properties in our entity bean implementation classes are not declared
    in our descriptor files, and therefore, are non-persistent (we are using container-managed
    persistence); I will refer to these properties as "non-persistent properties".
    In WebLogic 5.1, we've noticed that the non-persistent properties are cached in
    between transactions. For instance, I ask for a particular Person (Person(James)),
    and I set one of the non-persistent properties (Property(X)) inside Transaction(A).
    In Transaction(B) (which is exclusive of Transaction(A)), I access Property(X)
    and find that it is the same value as I had set in Transaction(A)- this gives
    the appearance that non-persistent entity properties are being cached in between
    transactions.
    The same appears to hold true in WebLogic 7 SP1, however, we must use the "Exclusive"
    concurrency-strategy to maintain this consistency.
    I am worried that this assumption we are making of non-persistent properties is
    not valid in all cases, and the documentation does not promise anything in the
    way of such an assumption. I am worried that the container could kill the Person(James)
    entity implementation instance in the pool after Transaction(A), and create a
    new Person(James) instance to serve Transaction(B)- once that happens our assumption
    fails.
    "Database" concurrency strategy seems to fail our assumption on a regular basis,
    but that makes sense, since the documentation states that the "database will maintain
    the cache", and the container seems more willing to kill instances when they are
    finished with, or create new instances for new transactions.
    So my question is this: What is exactly guaranteed by the "Exclusive" concurrency-strategy?
    Will the assumption that we've made above ever fail under this strategy?
    Thanks in advance for any help.
    Regards,
    James

    It simply means that there is only one entity bean instance per PK in the
    server, and transaction which uses it locks it exclusively.
    James DeFelice <[email protected]> wrote:
    Thank you for the suggestion. I have considered taking this path, but before I
    make a final decision, I was hoping to get a clear answer to the question that
    I stated below:
    What EXACTLY is guaranteed by the "Exclusive" concurrency-strategy? Maybe someone
    from BEA knows?
    "Cameron Purdy" <[email protected]> wrote:
    To be safe: You should clear those values before the ejb load or set
    them
    after (or both).
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com/coherence.jsp
    Tangosol Coherence: Clustered Replicated Cache for Weblogic
    "James DeFelice" <[email protected]> wrote in message
    news:[email protected]...
    Some of the properties in our entity bean implementation classes arenot
    declared
    in our descriptor files, and therefore, are non-persistent (we areusing
    container-managed
    persistence); I will refer to these properties as "non-persistentproperties".
    In WebLogic 5.1, we've noticed that the non-persistent properties arecached in
    between transactions. For instance, I ask for a particular Person(Person(James)),
    and I set one of the non-persistent properties (Property(X)) insideTransaction(A).
    In Transaction(B) (which is exclusive of Transaction(A)), I accessProperty(X)
    and find that it is the same value as I had set in Transaction(A)-this
    gives
    the appearance that non-persistent entity properties are being cachedin
    between
    transactions.
    The same appears to hold true in WebLogic 7 SP1, however, we must usethe
    "Exclusive"
    concurrency-strategy to maintain this consistency.
    I am worried that this assumption we are making of non-persistentproperties is
    not valid in all cases, and the documentation does not promise anythingin
    the
    way of such an assumption. I am worried that the container could killthe
    Person(James)
    entity implementation instance in the pool after Transaction(A), andcreate a
    new Person(James) instance to serve Transaction(B)- once that happensour
    assumption
    fails.
    "Database" concurrency strategy seems to fail our assumption on a regularbasis,
    but that makes sense, since the documentation states that the "databasewill maintain
    the cache", and the container seems more willing to kill instanceswhen
    they are
    finished with, or create new instances for new transactions.
    So my question is this: What is exactly guaranteed by the "Exclusive"concurrency-strategy?
    Will the assumption that we've made above ever fail under this strategy?
    Thanks in advance for any help.
    Regards,
    James
    Dimitri

  • Persist Entity Bean in flat file?

    Is it possible to persist entity bean in a flat file? I need to persist a single value (sequence number) and I can not use database to do so.
    I would need to run this in a clustered environment and need to recover the value if something goes wrong. The statefull bean would almost do except when one server fails before it replicates value onto another box.
    thx.

    Steve Edens wrote:
    I'm also trying to get a grip on the best way to handle some static application properties in a clustered environment. My need mostly relates to
    a need to read in some flat file type properties and then store them someplace
    where business logic can call them as needed.. Like a static hashmap or
    something. But someone mentioned Entity beans, BMP, etc..
    Now.. here's the strange part of the message.
    Back in 1999 I traveled over to our west coast office in San Francisco. I was meeting and greeting the staff there and along the way I had a short
    meeting with someone named Bisera Ferrero. I mention this event because I
    was really impressed with the beauty and charm of Bisera. Therefore, I guess
    I'm a fan. I rememered the name.. a little. Really, I had sort of forgotten
    about it until reading this forum this morning. So.. who knows. I guess
    there could be a lot of Bisera Ferrero names on our planet.
    Good luck in your quests..

  • 'pool' to 'ready' state of entity bean

    Entity bean's life cycle is show at http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts9.html#63498 Can entity bean go from �pooled� state to �ready� state by methods other than create (e.g. a find method)?

    How many questions are you going to ask at once?
    Most of these have been answered countless times, both here and on the web. Why don't you try searching instead of spewing endless questions?

  • Bean-Managed Persistent Entity Bean - SDA

    Hello,
    I wrote a BMP Entity Bean and it should use a data dictionary that i already have defined, but i do not know what should i write in the ejb-jar.xml file in order to get it works. Could you please tell me what should i write?
    <resource-ref>
      <res-ref-name>???</res-ref-name>
      <res-type>????<res-type>
    </resource-ref>
    Thanks for your help,
    SAPLernen

    Hello,
    I wrote a BMP Entity Bean and it should use a data dictionary that i already have defined, but i do not know what should i write in the ejb-jar.xml file in order to get it works. Could you please tell me what should i write?
    <resource-ref>
      <res-ref-name>???</res-ref-name>
      <res-type>????<res-type>
    </resource-ref>
    Thanks for your help,
    SAPLernen

  • Where to see the SQL statement that CMP Entity bean excuted?

    hi, I'm wondering where I can find the SQL that a CMP entity bean executed in a transaction?
    thank you!

    You can do it in many ways. If you are using eclipse then using eclipse
    plugins for weblogic you van do it. I have heard that in weblogic workshop
    also you can do it. If the above do doesn;t solves your problem then check
    this out.
    http://www.p6spy.com/documentation/install.htm
    Hope that helps.
    <Xin Zhuang> wrote in message news:[email protected]..
    hi, I'm wondering where I can find the SQL that a CMP entity bean executed
    in a transaction?
    thank you!

  • CMP Entity Bean with database specific features

    Hi there,
    I�m studying Entity Beans and I'm doing some experiences with SQL Server.
    At first, I built a CMP Bean and marked in deploytool to create the tables. Ok, it worked.
    Now, I'm trying to interact to an existent database. But, I got a problem: the primary key is defined by the Server. I can read it and I can remove entries. But, when I try to insert some entry, I can't pass the key in SQL statement. I edited the generated statement to do it, but it doesn't work. I get a RollbackException.
    My question is: is it possible to do what I'm intending to do with CMP? What am I doing wrong?
    Do you think that, to do this, I should use BMP Entity beans?
    Thanks in advance,
    Anicio

    "CMP provides you with database independence and less coding efforts."
    BMP is not database dependent, unless you invoke database specific things in your SQL (something I do not do). CMP on the otherhand is inherently appserver specific (which was it's goal when BEA, IBM, et al. came up with it), and still limits your design possibilities. See this thread for an example:
    http://forum.java.sun.com/thread.jsp?forum=13&thread=318785
    As for less coding effort, that is a relative statment. Yes a simple CMP bean requires less coding to develop the first time. I personally view a few lines of SQL to load and store the data as being fairly trivial. But that needs to be offset with the problems inherent in using appserver specific CMP implementations.
    As an example, try mapping WebSphere CMP to a pre-existing database without using IBM's IDE. It's an incredible pain in the ass since WebSphere does not come with a "meet-in-the-middle" solution. Any J2EE developer that has had the experience of working with different appservers (especially if they have had to port an app, as I have) can attest to the complications that arise with each implementation.
    A BMP bean, written with non-DB-specific SQL, is the most portable, most flexible approach to EntityBeans. Yes, it requires the developer to be able to write some SQL, which should not take a significant amout of time. WRT queries, you have to write them, either SQL, EQL, or some appserver specific format.
    As an aside, the use of code generators to simplify the creation of EJBs lends itself well to BMP. By using a (or writing your own) code generator, you can mitigate the annoying SQL bugs that creep up early in development.

  • CMP Entity Bean with ejb-ql finder methods and INFORMIX database

    Hi,
    I have some CMP Entity Beans with finder methods defined in ejb-ql. In my ejb-jar, within <entity> definitions I have something like:
        <entity>
          <abstract-schema-name>BeanName</abstract-schema-name>
          <cmp-field><field-name>fieldOne</field-name></cmp-field>
          <cmp-field><field-name>fieldTwo</field-name></cmp-field>
          <query>
            <query-method>
              <method-name>findAll</method-name>
              <method-params></method-params>
            </query-method>
            <ejb-ql>SELECT OBJECT(o) FROM BeanName o</ejb-ql>
          </query>
        <entity>
    And in persistent.xml:
    <db-properties>
         <data-source-name>datasource_name</data-source-name>
    </db-properties>
    <entity-bean>
         <ejb-name>BeanName</ejb-name>
         <table-name>table_name</table-name>
         <field-map key-type="NoKey">
         <field-name>fieldOne</field-name>
         <column><column-name>column_one</column-name></column>
          </field-map>
         <field-map key-type="NoKey">
         <field-name>fieldTwo</field-name>
         <column><column-name>column_two</column-name></column>
          </field-map>
          <finder-descriptor>
              <method-name>findAll</method-name>
              <method-params/>
         </finder-descriptor>
    Once deployed, on server side, I can found a java source file (with corresponding compiled class file) in path:
    j2ee/cluster/server0/apps/companyName/MyEARApp/EJBContainer/temp/temp38837373733/route/to/package/
    with names:
    BeanName0_0pm.java
    BeanName0_0PM.class
    and the generated java file contains this code:
      public java.util.Enumeration ejbFindAll() throws javax.ejb.FinderException, javax.ejb.EJBException  {
        TransactionContext tc = pm.getTransactionContext();
        Connection conn = null;
        PreparedStatement pSt = null;
        ResultSet ejb_rs = null;
        int status = javax.transaction.xa.XAResource.TMSUCCESS;
        try {
          conn = pm.getConnectionForFindMethod();
          pSt = conn.prepareStatement("SELECT \"O\".\"COLUMN_ONE\",\"O\".\"COLUMN_TWO\", FROM \"TABLE_NAME\" \"O\"");
          ejb_rs = pSt.executeQuery();
    I'm trying to call this method but it throws a SQLException when preparing the statement.
    It seems that Informix does not like this SQL syntax because of upper case names, doble quotes on table alias, or something else.
    When editing persistent.xml in netweaver, I can define the element <datasource-vendor> as ORACLE, SAPDB, MS_SQL_SERVER, DB2_UDB_AS400 or DB2_UDB_OS390 but INFORMIX is not an accepted value.
    Is there any way to define how this SQL query is build?
    Thanks in advance.

    The return type of the finder method defined in the remote home interface is either the entity bean's remote interface or a collection of objects implementing the entity bean's remote interface. The return type of the finder method defined in the local home interface is either the entity bean's local interface or a collection of objects implementing the entity bean's local interface

  • Very Basic Question about Entity Beans !!!  Need your help.

    Hi,
    I have the following requirement:-
    ==============================
    There is an application A, whose multiple instances can run
    at the same time. There is some data/variable which is to be
    globally shared (i.e by all the instances). I have thought of using
    Entity Beans and putting that data in a single record in DB.
    Approach A:-
    ~~~~~~~~~~~
    Instance 1 of A (with Entity Bean ) -
    -> Database (only 1 row exist)
    Instance 2 of A (with Entity Bean ) -
    Approach B:-
    ~~~~~~~~~~~
    Instance 1 of A
    -> Entity Bean -> Database (only 1 row exist)
    Instance 2 of A
    My Query is:-
    1) In Approach A, both the instances of Application
    have their own Entity Bean (running in same JVM as them,
    packaged with Application)..Now both the entity bean instances
    represent 1 row on Database...At one time only 1 Entity bean
    will be performing the operation (read/write, other will be
    disallowed).
    2) In Approach B, both the instances of application(or Client) using
    the same Entity Bean - which is representing 1 row of Database
    Which is correct....I have read somewhere instance of Entity Bean
    corresponds to 1 row of database....If that is the case, Approach
    A would be wrong..
    Please help.

    1 Entity bean for 1 row is not true. An entity bean can represent data from multiple tables also. The correct statement is 1Entitybean for 1 resultset.
    So in case 1, u have 2 instances of Application running so it should not be an issue.

  • Why Interceptors are not used in Entity beans?

    Why Interceptors are not used in Entity beans?
    Interceptors can be used in MDB, Session bean but not in Entity bean....why so?
    Thanks,
    Rahul.

    Hi,
    why batch updations are not prefered in entity beansPlease refer the specification of ejb and find out what the entity bean is meant for.In short the emtity bean represents the object state which can be persisted.
    Talking regarding the batch updations does not make sense , also the entity bean represents the row of the table mapped to the Object(java Object).
    Regards
    Vicky

  • Entity beans storing client callbacks...how?

    Ok, here's my situation. Multiple clients might be modifying the same entity bean so I have implemented client callbacks. A client registers a callback with the bean, and the bean will call it back when someone modifies the beans data.
    Now my question is entity beans can be removed by the container for various reasons, so how can I have the bean save the callback so when the container reloads the bean it reloads the callbacks? How do you store a callback to a database?
    Thanks,
    Jeff Plummer

    Shaft, let's look at it this way.
    How do you register a client as a callback? Anything "sent" to the EntityBean is serialized. That means when the EntityBean receives the information, it is not the same instance as your client class. Ergo, the "callback" method would operate only on the local instance the EntityBean has at the time, not the one on your client side.
    Now, as for the differences of "state." Yes, the EntityBean persists state as represented by the persistence store (e.g. a row in a table in database). However, in order to register an Object as you would for a callback, then the EntityBean must maintain a reference to that Object - which it can't because the only information that an EntityBean can maintain is that of the persistent store. Only static final Objects are allowed (ones that cannot change during the lifetime of an instance of the EntityBean). Even if you managed to circumvent this restriction, then you have to figure out how all of the EntityBeans would have exactly the same Object references for the callback objects.
    The only way to do what you want is to make it a "non-reference" type of relationship. Which means some sort of message-based system. If you use a JMS Topic, you can get a "broadcast" type of notification out to all your clients and, while there is a bit of a performance trade-off, it's a solution that will work.
    Finally, if there's "tons of data," you might want to go back and look at your Use Case(s) and determine if you really should be using EntityBeans anyway. EntityBeans are great stuff - when used in the right situations.

  • CMP Entity Bean from dataBase views

    Hi forum,
    I Have to migrate an existing application to JEE (with EJB3).
    In this application there are a lot of dataBase views.
    I'm new in EJB3 and I don't know how to structure cleanly entity beans (Specially when it are created from dataBase views).
    My problem is that for each query made from the same dataBase view I almost have to create a new entity bean with a different @Id.
    What can I do to to avoid it?
    I had thought to genrate a new @Id (attribute not persistent) but I think is not possible. It's right ?
    Someone can help me ?
    Thanks

    "CMP provides you with database independence and less coding efforts."
    BMP is not database dependent, unless you invoke database specific things in your SQL (something I do not do). CMP on the otherhand is inherently appserver specific (which was it's goal when BEA, IBM, et al. came up with it), and still limits your design possibilities. See this thread for an example:
    http://forum.java.sun.com/thread.jsp?forum=13&thread=318785
    As for less coding effort, that is a relative statment. Yes a simple CMP bean requires less coding to develop the first time. I personally view a few lines of SQL to load and store the data as being fairly trivial. But that needs to be offset with the problems inherent in using appserver specific CMP implementations.
    As an example, try mapping WebSphere CMP to a pre-existing database without using IBM's IDE. It's an incredible pain in the ass since WebSphere does not come with a "meet-in-the-middle" solution. Any J2EE developer that has had the experience of working with different appservers (especially if they have had to port an app, as I have) can attest to the complications that arise with each implementation.
    A BMP bean, written with non-DB-specific SQL, is the most portable, most flexible approach to EntityBeans. Yes, it requires the developer to be able to write some SQL, which should not take a significant amout of time. WRT queries, you have to write them, either SQL, EQL, or some appserver specific format.
    As an aside, the use of code generators to simplify the creation of EJBs lends itself well to BMP. By using a (or writing your own) code generator, you can mitigate the annoying SQL bugs that creep up early in development.

  • Entity bean mapping to multiple tables.

    Hello,
    Is it possible to map several tables with only one BMP?
    if so please send me an example (class bean)
    Thanks in advance

    hi,
    yes, entity bean can be mapped to multiple tables provided it is bean managed entity bean.
    since, container cannot prepare complex quries so that we need to rely on bean managed persistance.
    Ex : Assume you have two table like X, Y
    where X table having fields (int x primarykey, varchar str) and Y table having fields (varchar name primarykey, int y).
    Now you should design a primary key class of your own as shown below:
    public class BeanPriamkey implements java.io.Serializable
    protected int x;
    protected String name;
    public BeanPramkey()
    //initialzation part
    public BeanPramkey(int x,String str)
    //initialzation part
    public String toString()
    //return object value as string
    public int hashCode()
    //return an int value
    public boolean equals(BeanPramkey)
    public int getX()
    return x;
    public String getStr()
    return str;
    now your entity bean would be like this
    public class Mybean implements EntityBean
    int x,y;
    String str,name;
    BeanPriamkey primekey;
    public BeanPrrmkey ejbCreate(int x,String name)
    //fetch the rows from the tables X and Y ;
    //if the rows exists int the tables create beanprimkey object with x and name and return refernce of the Beanprimkey class object
    public BeanPrimkey findByPrimarykey(BeanPrimkey )
    //first extract values of x and str from BeanPrimkey
    and chek X and Y table for corresponding rows if exists return the reference of BeanPrimkey else return null
    public void ejbStore()
    BeanPrimkey prikey = (BeanPrimkey) entityContext.getPrimarykey();
    int x = prikey.getX();
    String st = prikey.getStr();
    update X and Y tables using x and str;
    public void ejbLoad()
    BeanPrimkey prikey = (BeanPrimkey) entityContext.getPrimarykey();
    int x = prikey.getX();
    String st = prikey.getStr();
    fetch the rows from X and Y tables using x and str;
    and assing the row values to bean instance variables.
    public void ejbPassivate()
    //code for release the resources
    public void ejbActivate()
    //code for aquiring the resource
    public void setEntityContext(EntityContext ec)
    this.ec = ec;
    protected EntityContext ec;

Maybe you are looking for