Entity question

Hy,
I have a simple question regarding entities. Are entity relationships retrieved from the database?
For example, if I have two entities:
EntityA.java
@Entity
public class EntityA {
    private EntityB b;
    @OneToOne(mappedBy="a")
    public EntityB getB() {
        return b;
    public void setB(EntityB b) {
        this.b = b;
EntityB.java
@Entity
public class EntityB {
    private EntityA a;
    @OneToOne
    public EntityA getA() {
        return a;
    public void setA(EntityA a) {
        this.a = a;
}If I retrieve an instance of EntityA, say with EntityManager#find(), can I access the EntityB instance through EntityA#getB()? And if I can, how does it work? Does the persistence provider instanciate an EntityB the first time I call EntityA#getB() and return the same reference on subsequent calls to getB()?
Thanks,
Csabi

Hi Frank,
I did as you suggested and moved all attributes in the properties file relating to 'the applicant' or 'the entry clearance officer' from Global into the relevant entity. One annoying thing when you are cutting and pasting a large number of attributes; once pasted they all take on the same ID.
Also, when creating entities in the properties file, why doesn't it automatically recognise the attributes that relate to it?
I then stripped and removed all attributes from all the documents in the project and recompiled them and this ended the problem
However, I'm still getting error message for the screens which collect attributes that relate to these singleton entities or the global entity (e.g. 'Screen belongs to entity 'the applicant' which is not collected from entity 'Global').
I thought that there was no restriction on collecting singletons on the same screen as attributes relating to the global entity? I'm also getting similar errors on a screen flow diagram in which these screens appear.
Regards,
Matt

Similar Messages

  • Webaccess for External Entity questions

    Hello,
    - We are not able to logon to our external entities with webaccess (only with delegate option in the client)
    - We have a password policy set to an edir object "login.policy", so this is for everyone.
    on the password policy we've configured "periodic password change"=90 "require password"=yes /etc.
    - We are authenticate to groupwise /edirectory with LDAP, so external entities should be use Groupwise password.
    I have 2 questions:
    - I want to disable the password policy "periodic password change" for this external entities.
    Is it true that password policies are affected for external entities and if yes how can i exclude that, since i cannot assign a password policy to groupwise objects (only to users)
    - I'm not able to login to the external entities with webaccess "mailbox not available" while i set manual the groupwise password in the external entity object. But i see that direct after that the password policy set the periodic password change to "current date/time"
    How can i solve this, what's the best practice for this.
    Thanks.

    Hi,
    We are using the latest one 8.02 HP2
    hmm you don't have problems...
    For information:
    When i create an external entity:
    Within consoleOne: select the postoffice > new > external entity
    then i put in each field the same name as example : "mailaddress"
    Then i have to browse for the object to place. There i place it in my Edir-tree under users/department/*
    When i'm open the properties of the external entity and go to restrictions:
    there everything is selected, so also "Force periodic password change", exactly the same as for our other users. (so that's the policy i think)
    But when i deselect the "force periodic", it's good. But then when i say "change password", it's getting his password policy back from the server and there it is selected again.
    But in the meantime i still cannot login with it.
    I have 1 external entity that was working at a moment, don't know what i did. Ten times the same procedure. But also the password policy is there.
    Is the structure the problem, where do you have the external entity object in your edir placed?
    Originally Posted by kjhurni
    What version of WebAccess do you have?
    We use LDAP against eDir for our GroupWise system, and we also have "external entities" (as such, they're only in the GW system) and don't have any problems at all with the external entities logging in.
    Obviously since the external entities are ONLY in GW, there is no NMAS Universal Password Policy that can apply to them, so I'm confused as to why an external entitity in your case would even be prompted every X days to change a password.

  • HTML Entity Question

    ▼ nicely displays a downward facing solid triangle in Firefox
    IE6 will not display it.
    Will IE7 or later versions show it?
    Many thanks for your attention, it is appreciated.

    This is not my issue. Your forums site doesn't work very well.
    My Issue:
    I just upgraded my PC from XP Professional 32-bit with CS4 to Win 7 64-bit  with CS5. I created and used 4 master templates (not nested) in CS4 which ran perfectly. Since I upgraded to CS5, I am unable to update the child pages at all. I mean it is DOA!! I downloaded an update fixer from Adobe but that seemed to be for the extension manager, not updating pages from a template. I tried all the usual template commands such as Update Current Page, etc....When I tried the command Open Attached template, the message I got  was that I was denied access, but I manually opened it just fine. (@#$%@#$%&%^&$&*)
    What can I do to get my DW to update?

  • How to check whether  entity has been persisted in the current transaction

    Hello,
    I am porting functionality which relay heavily on lifecycle of the entity.
    For example methods like these:
    * returns true if the instance has been modified, deleted or newly made
    * persistent in the current transaction
    public boolean isModified(final EntityObject entity)
    public boolean isDeleted(final EntityObject entity)
    For some of these callsI have found how to port them to toplink und just want to validate that this is the right way:
    protected static UnitOfWork getUnitOfWork(EntityManager entityManager) {
    return ((JpaEntityManager) (entityManager.getDelegate())).getUnitOfWork();
    public static boolean isModified(EntityManager entityManager, Object entity) {
    UnitOfWorkChangeSet set = getUnitOfWork(entityManager).getCurrentChanges();
    ObjectChangeSet oset = set.getObjectChangeSetForClone(entity);
    return !oset.getChanges().isEmpty() || oset.isNew();
    public static boolean isDeleted(EntityManager entityManager, Object entity) {
    UnitOfWorkChangeSet set = getUnitOfWork(entityManager).getCurrentChanges();
    return set.getDeletedObjects().keySet().contains(entity);
    but I did not find how to do following with the eclipselink:
    * returns true, if the given entity object has been persistet during the
    * current transaction
    * @param entity
    * @return true, if the given entity object has been persistet during the
    * current transaction
    public boolean isPersistent(final EntityObject entity)
    Questions:
    - how can I check whether the entity is persistent in the sense already stored in the DB ?
    - how can I check whether the entity has been persisted in the current transaction ?
    Thanks in advance.
    Andre Teshler

    Hi Andre,
    In Eclipse link there are Entity listeners which will define the life cycle events like preInsert(),postInsert() etc.On successful insertion of an object its postInsert() life cycle method gets called.If you have to validate whether object inserted successfully then best place is to override the postInsert() and check for the existence of the record.All the event life cycle methods take a DescriptorEvent as parameter which will give handle to API as given below.In the same method you can check if this insert operation succeeded in the same transaction.
    package model;
    import java.util.Vector;
    import org.eclipse.persistence.descriptors.DescriptorEvent;
    import org.eclipse.persistence.descriptors.DescriptorEventAdapter;
    import org.eclipse.persistence.descriptors.DescriptorEventListener;
    import org.eclipse.persistence.internal.sessions.ObjectChangeSet;
    public class SampleEntityLIstener extends DescriptorEventAdapter {
    public SampleEntityLIstener() {
    super();
    public void postInsert(DescriptorEvent event) {
    event.getRecord().containsKey("pass the object");
    event.getChangeSet().getUOWChangeSet();
    public void preInsert(DescriptorEvent event) {
    Once you implement the DescriptorEventListener,need to register with the Entity so that life cycle methods gets called and respective business logic gets executed.
    Hope this helps,
    Regards,
    P.Vinay Kumar

  • Noob Question: Problem with Persistence in First Entity Bean

    Hey folks,
    I have started with EJB3 just recently. After reading several books on the topic I finally started programming myself. I wanted to develop a little application for getting a feeling of the technology. So what I did is to create a AppClient, which calls a Stateless Session Bean. This Stateless Bean then adds an Entity to the Database. For doing this I use Netbeans 6.5 and the integrated glassfish. The problem I am facing is, that the mapping somehow doesnt work, but I have no clue why it doesn't work. I just get an EJBException.
    I would be very thankfull if you guys could help me out of this. And don't forget this is my first ejb project - i might need a very detailed answer ... I know - noobs can be a real ....
    So here is the code of the application. I have a few methods to do some extra work there, you can ignore them, there are of no use at the moment. All that is really implemented is testConnection() and testAddCompany(). The testconnection() Methode works pretty fine, but when it comes to the testAddCompany I get into problems.
    Edit:As I found out just now, there is the possibility of Netbeans to add a Facade pattern to an Entity bean. If I use this, everythings fine and it works out to be perfect, however I am still curious, why the approach without the given classes by netbeans it doesn't work.
    public class Main {
        private EntryRemote entryPoint = null;
        public static void main(String[] args) throws NamingException {
            Main main = new Main();
            main.runApplication();
        private void runApplication()throws NamingException{
            this.getContext();
            this.testConnection();
            this.testAddCompany();
            this.testAddShipmentAddress(1);
            this.testAddBillingAddress(1);
            this.testAddEmployee(1);
            this.addBankAccount(1);
        private void getContext() throws NamingException{
            InitialContext ctx = new InitialContext();
            this.entryPoint = (EntryRemote) ctx.lookup("Entry#ejb.EntryRemote");
        private void testConnection()
            System.err.println("Can Bean Entry be reached: " + entryPoint.isAlive());
        private void testAddCompany(){
            Company company = new Company();
            company.setName("JavaFreaks");
            entryPoint.addCompany(company);
            System.err.println("JavaFreaks has been placed in the db");
        }Here is the Stateless Session Bean. I added the PersistenceContext, and its also mapped in the persistence.xml file, however here the trouble starts.
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    @Stateless(mappedName="Entry")
    public class EntryBean implements EntryRemote {
        @PersistenceContext(unitName="PersistenceUnit") private EntityManager manager;
        public boolean isAlive() {
            return true;
        public boolean addCompany(Company company) {
            manager.persist(company);
            return true;
        public boolean addShipmentAddress(long companyId) {
            return false;
        public boolean addBillingAddress(long companyId) {
            return false;
        public boolean addEmployee(long companyId) {
            return false;
        public boolean addBankAccount(long companyId) {
            return false;
    }That you guys and gals will have a complete overview of whats really going on, here is the Entity as well.
    package ejb;
    import java.io.Serializable;
    import javax.persistence.*;
    @Entity
    @Table(name="COMPANY")
    public class Company implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        @Column(name="COMPANY_NAME")
        private String name;
        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;
            System.err.println("SUCCESS:  CompanyName SET");
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (id != null ? id.hashCode() : 0);
            return hash;
        @Override
        public boolean equals(Object object) {
            // TODO: Warning - this method won't work in the case the id fields are not set
            if (!(object instanceof Company)) {
                return false;
            Company other = (Company) object;
            if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
                return false;
            return true;
        @Override
        public String toString() {
            return "ejb.Company[id=" + id + "]";
    }And the persistence.xml file
    <?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="PersistenceUnit" transaction-type="JTA">
        <provider>oracle.toplink.essentials.PersistenceProvider</provider>
        <jta-data-source>jdbc/sample</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
          <property name="toplink.ddl-generation" value="create-tables"/>
        </properties>
      </persistence-unit>
    </persistence>And this is the error message
    08.06.2009 10:30:46 com.sun.enterprise.appclient.MainWithModuleSupport <init>
    WARNUNG: ACC003: Ausnahmefehler bei Anwendung.
    javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.RemoteException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.; nested exception is:
            javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.RemoteException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.; nested exception is:
            javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.
            at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:243)
            at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:205)
            at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:152)
            at com.sun.corba.ee.impl.presentation.rmi.bcel.BCELStubBase.invoke(BCELStubBase.java:225)
            at ejb.__EntryRemote_Remote_DynamicStub.addCompany(ejb/__EntryRemote_Remote_DynamicStub.java)I spend half the night figuring out whats wrong, however I couldnt find any solution.
    If you have any idea pls let me know
    Best regards and happy coding
    Taggert
    Edited by: Taggert_77 on Jun 8, 2009 2:27 PM

    Well I don't understand this. If Netbeans created a Stateless Session Bean as a facade then it works -and it is implemented as a CMP, not as a BMP as you suggested.
    I defenitely will try you suggestion, just for curiosity and to learn the technology, however I dont have see why BMP will work and CMP won't.
    I also don't see why a stateless bean can not be a CMP. As far as I read it should not matter. Also on the link you sent me, I can't see anything related to that.
    Maybe you can help me answering these questions.
    I hope the above lines don't sound harsh. I really appreciate your input.
    Best regards
    Taggert

  • Questions about entity bean caching/pooling

    We have a large J2ee app running on weblogic6.1 sp4. We are using entity beans
    with cmp/cmr. We have about 200 EntityBeans and accessed quite heavily. We are
    struggling with what is the right setting of max-beans-in-cache and idle-time-out.
    The current max heap setting is 2GB. With the current setting (default setting
    of max-beans-in-cache to 1000, with a few exceptions to take care of cachefullexceptions)
    we run into extended gc happening after about 4 hours. The memory freed gradually
    reduces with time and lurks around the 30% mark after about 4 hours of run at
    the expected load. In relation to this we had the following questions
    1. What does caching mean?
    a. If a bean with primary key 100 exists in the cache, and the following
    is done what is expected
    i. findByPrimaryKey(100)
    ii. findBySomeOtherKey(xyz)
    which results in loading up bean with primary key 100
    iii. cmr access to bean with
    primary key 100
    Is the instance in the cache reused at all between transactions?
    If there is minimal reuse of the beans in cache, Is it fair to assume that caching
    can only help loading of beans within a transaction. If this is the case, is there
    any driver to increase the max-beans-in-cache other than to avoid CacheFullException?
    In other words, is it wrong to say that max-beans-in-cache should be set to the
    minimum value so as to avoid CacheFullExceptions.
    2. Again what is the driver of setting idle-time-out to a value? ( We currently
    have it at 30 secs) Partly the answer to this question would again go back to
    what amount of reuse is done from cache? Is it right to say that it should be
    set to a very low value? (Why is the default 10 min?)
    3. Can you provide us any documentation that explains how all this works
    in more detail, particularly in relevance to entity beans. We have already read
    the documentation from weblogic as is. Anything to give more explicit detail?
    Any tools that can be of use.
    4. What is the right parameter (from among the things that weblogic console
    throws up) to look at for optimizing?
    Thanks in advance for your help
    Cheers
    Arun

    The behaviour changes according to these descriptor settings: concurrency-strategy,
    db-is-shared and include-updates.
    1. If concurrency-strategy is Database, then the database is used to provide locking
    and db-is-shared is ignored. A bean's ejbLoad() is called once per transaction,
    and the 'cache' is really a per-transaction pool. A findByPrimaryKey() always
    initially hits the db, but can use the cache if called again in the same txn (although
    you'd simply just pass a reference around). A findByAnythingElse() always hits
    the db.
    2. If concurrency-strategy is ReadOnly then the cache is longer-term: ejbLoad()
    is only called when the bean is activated; thereafter, the number of times ejbLoad()
    is called is influenced by the setting of read-timeout-seconds. A findByPrimaryKey()
    can use the cache. A findByAnythingElse() can't.
    3. If concurrency-strategy is Exclusive then db-is-shared influences how many
    times ejbLoad() is called. If db-is-shared is false (i.e. the container has exclusive
    use of the underlying table), then the ejbLoad() behaviour is more like ReadOnly
    (2. above), and the cache is longer-term. If db-is-shared is true, then the ejbLoad()
    behaviour is like Database (1. above).
    Exclusive concurrency reduces ejbLoads(), increases the effectiveness of the cache,
    but can reduce app concurrency as only one instance of an entity bean can exist
    inside the server, and access to it is serialised at the txn level.
    You can't use db-is-shared = false in a cluster. So Exclusive mode is less useful.
    That's when you think long and hard about Tangosol Coherence (http://www.tangosol.com)
    4. If include-updates is true, then the cache is flushed to the db before every
    non-findByPrimaryKey() finder call so the finder (which always hits the db) will
    get the latest bean values. This overrides a true setting of delay-updates-until-end-of-tx.
    The max-beans-in-cache setting refers to the maximum number of active beans (really
    beans that have been returned by a finder in a txn that hasn't committed). This
    wasn't checked in SP2 (we have an app that accidently loads 30,000 beans in a
    txn with a max-beans-in-cache of 3,000. Slow, but it works, showing 3,000 active
    beans, and 27,000 passivated ones...).
    This setting is checked in SP5, but I don't know about SP4. So you do need to
    size appropriately.
    In summary:
    - The cache isn't nearly as useful as you'd like. You get far more db activity
    with entity beans than you'd like (too many ejbLoads()). This is disappointing.
    - findByPrimaryKey() finders can use the cache. How long the cache is kept around
    depends on concurrency-strategy.
    - findByAnythingElse() finders always hit the db.
    WebLogic 8 tidies all this up a bit with a cache-between-transactions setting
    and optimistic locking. But I believe findByAnythingElse() finders still have
    to hit the db - ejbql is never run against the cache, but is always converted
    to SQL and run against the db.
    Hope this is of some help - feel free to email me at simon-dot-spruzen-at-rbos-dot-com
    (you get the idea!)
    simon.

  • Please I would need the  correct Entity Diagram for this Two questions.

    This is to draw an Entity Relationship Modelling Diagram that will show inside dot for the "Must Need" end and outside dot on the "not must" end.
    You also need to put 1s and Ms relationship where needed.
    Question (1)
    The All Day Driving School
    The All Day Driving School has a number of instructors. Each instructor is assigned a car for their own use only.
    The school also has a spare car which is not assigned to a particular instructor.
    The driving school takes on pupils who are each allocated to an instructor. The pupil then books lessons with the instructor.
    New instructors have a short induction period before any pupils are allocated to them.
    Suggest suitable attributes for each table (assume that these will be discussed in detail with the user when you next meet with them).
    Extention to the scenario: Sometimes the pupil´s allocated instructor is not available when he/she requires a lesson, and a different instructor cover that lesson.
    How would you amend your diagram and tables so that it is still possible to identify the allocated instructor, but also to record who was the instructor for each lesson?.
    MY Answer:
    Attributes:
    Institution(InstitutionID, Name, Address, Telephone, Location)
    Instructor(InstructorID, Fname, Lname, Address, DOB, Gender)
    Car(CarID, RegistrationNo, Make, Model, Colour)
    Pupil(PupilID, IntructorID, LessonID)
    Lesson(LessonID, InstructorID, CarID, StartDate, EndDate, Cost, Details)
    Question (2)
    This is to draw an Entity Relationship Modelling Diagram that will show inside dot for the "Must Need" end and outside dot on the "not must" end.
    You also need to put 1s and Ms relationship where needed.
    London Allotments
    London City Council’s allotment department is responsible for the city’s allotments. Allotments are small areas of land that can be rented by council residents to grow vegetables and fruits. These allotments are rented by individuals. A site may have a paid manager who looks after the site and carries out any maintenance (such as repairing gates and fences): in this case, basic details of the manager are stored. As the site are spread throughout the city, each manager looks after exactly one site. A gardener rents a numbered allotment by paying the rented fee. Some gardeners rent several allotments but an allotment can only be rented by one named person. The allotments are in great demand and are never left vacant. Gardener’s details are recorded as soon as they are accepted for the waiting list,
    together with the date they were added to the list.
    Suggest suitable attributes for each table(assume that these will be discussed in details with the users when you next meet with them)
    Extension to the scenario: This scenario encourages you to draw an ERD that records only the current manager of each site, not previous managers. Similarly you
    were only expected to record the current gardener for each allotment. How would your diagram change if the council wanted to keep records of all the managers
    and gardners over several years? Does the basic rule for allocating foreign keys work for the new diagram? We are going to need more techniques, aren´t we?
    My Answer:
    Attributes:
    Council(CouncilID, Address, Telephone, Location)
    Manager(ManagerID, Fname, Lname, Address, DOB, Gender)
    Site(SiteID, RegistrationNo, Size, Location)
    Gardener(GardenerID, , Lname, Address, DOB, Gender)
    Allotment(AllotmentID, RentalFee, NameOnRent, AllocatedDate, ExpiryDate, RentDuration, AllocationSize, WaitingList)
    Individual(IndividualID, Fname, Lname, Address, DOB, Gender)

    This is to draw an Entity Relationship Modelling Diagram
    NOTHING involving Oracle exists in problem or solution.
    Problem can apply to any RDBMS.
    BTW, we don't do homework assignments.

  • Newbie question about entity and view objects

    Hi everyone,
    My first ADF application in JDeveloper is off to a difficult start. Having come from a forms background, I know that it is necessary avoid using post-query type lookups in order to have full filtering using F11/Ctrl+F11. This means creating an CRUDable view and getting as much of the lookup data as possible into the view without losing the ability to modify the data. In JDeveloper, I do not know how to build my data model to support that. My thought was to start with a robust updateable view as my main CRUD EO and then create a VO on top of that with additional EOs or VOs. But, I have found that I cannot add VOs to another VO. However, if I link the VOs then I have a master-detail which will not work for me.
    For example, I have two joins to CSI_INST_EXTEND_ATTRIB_V shown in the queries below and need to have that show in the table displaying the CRUD VO’s data. It seemed that the best way to do this is to create a CSI_INST_EXTEND_ATTRIB_V entity object and view object. The view object would have two parameters, P_INSTANCE_ID and P_ATTRIBUTE name. Both the building and the unit are needed on the same record, and this is not a master-detail even though it might look that way. (A master-detail data control will not work for me because I need all this data to appear on the same line in the table.) So, I need help figuring out the best way to link these to the main (CRUD) view; I want as much of this data as possible to be filterable.
    select
    cieav.attribute_value
    from
    csi_inst_extend_attrib_v cieav
    where cieav.instance_id = p_instance_id
    and cieav.attribute_code = 'BUILDING NAME'
    select
    cieav.attribute_value
    from
    csi_inst_extend_attrib_v cieav
    where cieav.instance_id = p_instance_id
    and cieav.attribute_code = 'UNIT NAME'
    Ultimately, I need to display a ton of data in each record displayed in the UI table, so a ton of joins will be needed. And, I need to be able to add records using the UI table also.
    James

    Hi Alejandro,
    Sorry if I caused confusion with my first post. What I had in mind assumed that I could have a single CSI_INST_EXTEND_ATTRIB_V EO with a BuildingVO and UnitVO on top of it. So, I wrote the queries individually to show how I would invoke each view. When I realized that confused the issue, I rewrote the query to explain things better.
    Now having seen your 2 queries. You need to create 2 EO. One for each table. Then create an association between the 2 aeO (this will be the join you are talking about). Then, you need to create a VO based on one of the EO and after you can modify and add the second EO (in here you select the join type).
    After your done with this, youll have 1 VO that supports CRUD in both tables.
    There were three tables in the query: CIEAV_BUILDING, CIEAV_UNIT, and T -- the main CRUD table. When you say that I should create two EOs, do you mean that they are to be for CIEAV_BUILDING and CIEAV_UNIT? Or, CIEAV and T? Assuming CIEAV and T, that sounds like it would allow me to show my building or unit on the record but not both.
    By the way, everything is a reference except for the main CRUD table.
    Look forward to hearing from you. Thanks for your help (and patience).

  • EJB 3.0 question - saving an entity bean containing another entity bean

    Hi,
    First, I want to store an entity bean. Secondly, I want to store another entity bean - containing the first entity bean.
    I have the following code in a session bean for this:
    public void saveFeedScheduling(FeedScheduling feedScheduling, FeedSource feedSource) {
    FeedSource feeds = em.merge(feedSource);
    em.flush();
    feedScheduling.setFeedSource(feeds);
    FeedScheduling feedSched = em.merge(feedScheduling);
    em.flush();
    This seems to work fine - still, is this the proper way to do it?

    Hello,
    This kind of parameter can be specified using the relationship annotation.
    I'm not 100% sure, but, lok at the "cascade element".
    Regards,
    Sebastien Degardin

  • Question: is there any way to get entity class in JPQL query

    Hello, I'm using J*dev 11gR1 adn JPA with EclipceLink*.
    Let's consider such example
    @Entity
    @Table(name="ANIMALS")
    @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
    public class Animal implements Serializable {
    @Entity
    @Table(name = "CATS")
    public class Cat extends Animal implements Serializable{
    @Entity
    @Table(name = "DOGS")
    public class Dog extends Animal implements Serializable{
    }I need to build a query which will be translated to something like this SQL query:
    SELECT * FROM CATS
    UNION ALL
    SELECT * FROM DOGS
    ORDER BY ...So I need a way to query not all child entities from DB.
    P.S. Yes, I know, that I can execute query on panent entity (select a from Animal a order by ...) and then loop throught the result list and delete not needed objects OR I can execute some queries on needed child entities and then merge them into one list and sort it, BUT both ways it will be much slower than generetion of needed SQL query straight to DB.
    I know, that in Hibernate's HQL there is a way to build such query with something like this:
    select * from Animal a where a.class = Cat or a.class = Dog

    In JPA 2.0 which we are implementing right now you will be able to execute queries like:
    SELECT a FROM Animal a  WHERE TYPE(a) IN (Cat, Dog)The next draft of the specification contains a section which describes the feature in detail and provides more examples of its use:
    4.6.17.4 Entity Type Expressions
    An entity type expression can be used to restrict query polymorphism. The TYPE operator returns the
    exact type of the argument.I have also been working with some customers on similar capabilities using the current versions of EclipseLink. The examples are documented here:
    http://wiki.eclipse.org/EclipseLink/Development/JPA/QueryDownCast
    I hope this helps,
    Doug

  • 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.

  • Newbie question on Java Persistence API - Entity Beans

    Hi All,
    I am basically new to Entities and the Java Persistence API. My question is, when using a container managed EntityManager, do I have to manually tidy-up any resources? Say for example, do I have to explicitly close the database connection (if ever I have that ability)? Invoke close() on EntityManager?
    - Pat

    You don't have to. That's what they mean by container managed. The container does it for you.
    In fact you will get an IllegalStateException if you call close on a container-managed EntityManager.

  • Question on Persistence (Entity Beans, Hibernate, JDBC)

    Hi everybody!
    Until now, I have read a lot about persistence in the J2EE-sector, but I am still confused about which technology to used in my case.
    I hope, that maybe you can give me some hints, by telling me which technology is good or bad regarding my requirements:
    I want to build a customer- and order-management system fullfilling the following requirements:
    1. The client is a Java application, the server is a JBOSS 4.0.1
    2. The databasa scheme exists already and I'm not allowed to change it.
    Some data, that logically belongs together and which shall be presented together to the client is distributed over 2 database tables.
    3. The user cannot just create new and view data, but will also edit existing data quite often.
    4. The user can assign products to an order. Often, there will be more than 1000 products assigned to an order, which will be presented to the user as a table (e.g. JTable). The user can then edit each cell of that 1000-row table, which of course will lead to an update in the db.
    5. The user can also assign customers to a specific role in an order-process. On the other hand, each customer can make many orders.
    So, we have a n:m relation here with the db-tables Customer, Order, OrderCustomer.
    6. A complex search functionality has to be implemented, where the db-query is created dynamically at runtime.
    7. The application is a multi-user application (about 10 users). It will be very rare, that users will work on the same data at the same time, but it might happen.
    8. The database type (SAP DB) will not be changed in the near future.
    With these 8 requirements in mind, I dealed a lot with EntityBeans, Hibernate and JDBC with SesseionBeans during the last 2 weeks.
    Until now, I came to the following conclusions.
    Hibernate is too slow. That'S bad, for data is edited very often and sometimes I want to edit just a single cell in 1000-row table.
    Hibernate's biggest advantage - that it makes your application independent of the database type - is not even required (see point 8).
    JDBC with SessioBeans: Very fast (I tried a simple query and it was about 10 times faster than Hibernate).
    The disadvantage is, that I have to take care about all the transaction, concurrency control etc. things.
    If I use JDBC, I want to do it that way: A SessionFacade accesses a DAO-object which executes the DB-query and returns the result to the SessionFacade which in the last step will pass the result to the client.
    Entity Beans: I am completely confused with Entity Beans.
    I read a lot about the CompositeEntity-Pattern for BMP. But on sun's J2EE Pattern page (http://java.sun.com/blueprints/corej2eepatterns/Patterns/CompositeEntity.html)
    they said, that it's just useful when using the EJB 1.1 specification, because from EJB 2.0. the container or whatever will take care about lazy loading and store optimization.
    So, from EJB 2.0. you should prefer using CMP-Beans with Container Managed Relationships (CMR), but as I heard, the dependent objects cannot be accessed and changed by the client when using CMPBeans with CMR.
    However, a simple DB/Entity-mapping will not work in my case, because as mentioned above, there are thousands of products from the db to be managed at the same time. So here, I thought, the Composite pattern with its lazy loading strategy would be useful.
    Furthermore, I have an n:m relationship in my database scheme, which is not trivial to map to entity beans. And don't forget that some related data is spread over 2 databse tables.
    To sum it up, it would be very nice if some of you could clarify this perisistence nightmare, especially some clarification about if and how to use EntityBeans when having n:m relationships, editing data a lot, managing lots of table rows at once and having related data distributed over 2 database tables.
    So, which technology would you prefer with the 8 requirements in mind? Hibernate, Entity Beans or JDBC with SessionBeans? Or would you prefer a mixed solution?
    Thanx for every hint.
    Regards,
    egon

    Here the requested information about the test:
    Goal:
    Find all customers, who's branches have the String "Branch" in their name.
    Both times, a simple client accesses the same SessionBean in a JBOSS-Container.
    This Bean has 2 methods. One accesses the DB via Hibernate (executeCriteria), the other one via JDBC (executeCriteriaJDBC).
    The code to count the seconds of computation is as follows:
    long startTime = System.currentTimeMillis();
    List customerList = bean.executeCriteria(dc);
    System.out.println("Hibernate: "+((System.currentTimeMillis()-startTime)/1000.0f)+" sek");
    startTime = System.currentTimeMillis();
    List customerListJDBC = bean.executeCriteriaJDBC(query);
    System.out.println("JDBC: "+((System.currentTimeMillis()-startTime)/1000.0f)+" sek");
    HIBERNATE:
    CODE:
    Branch Branch = new Branch();
    Branch.setName("%Branch%");
    Example example = Example.create(Branch);     
    DetachedCriteria dc = DetachedCriteria.forClass(Customer.class)
    .createCriteria("branches").add(example.enableLike()).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    QUERY:
    select
            this_.UUID as UUID1_1_,
            this_.NAME as NAME1_1_,
            this_.CUSTOMERNO as CUSTOMERNO1_1_,
            this_.SHORTDESC as SHORTDESC1_1_,
            this_.LONGDESC as LONGDESC1_1_,
            this_.TAXNUMBER as TAXNUMBER1_1_,
            this_.SALESTAXID as SALESTAXID1_1_,
            this_.ACCOUNTHOLDER as ACCOUNTH8_1_1_,
            this_.BANKACCOUNT as BANKACCO9_1_1_,
            this_.BANKCODE as BANKCODE1_1_,
            this_.BANKNAME as BANKNAME1_1_,
            this_.AREA1TEXT as AREA12_1_1_,
            this_.AREA2TEXT as AREA13_1_1_,
            this_.AREA3TEXT as AREA14_1_1_,
            this_.AREA4TEXT as AREA15_1_1_,
            this_.AREA5TEXT as AREA16_1_1_,
            this_.CH_UUID as CH17_1_1_,
            this_.REFTEXT1 as REFTEXT18_1_1_,
            this_.REFTEXT2 as REFTEXT19_1_1_,
            this_.REFTEXT3 as REFTEXT20_1_1_,
            branch1_.UUID as UUID0_0_,
            branch1_.NAME as NAME0_0_,
            branch1_.ILN as ILN0_0_,
            branch1_.BRANCHID as BRANCHID0_0_,
            branch1_.SHORTDESC as SHORTDESC0_0_,
            branch1_.LONGDESC as LONGDESC0_0_,
            branch1_.BAGSRECEIVED as BAGSRECE7_0_0_,
            branch1_.CUSTOMER_UUID as CUSTOMER8_0_0_
        from
            CUSTOMER this_,
            BRANCH branch1_
        where
            this_.UUID=branch1_.CUSTOMER_UUID
            and (
                branch1_.NAME like ?
    RESULT:
    Customername: Customer_A
    Customername: Customer_F
    Customername: Customer_D
    Customername: Customer_R
    Customername: Customer_S
    TIME:
    Hibernate: 1.343 sek
    JDBC:
    QUERY:
    Select distinct c.* from Customer c, Branch b where b.id=b.Customer_id and b.name like '%Branch%'
    // After getting the result of the query: Create a list of Customer-objects. Set all attributes of each Customer-object.
    RESULT:
    Customername: Customer_R
    Customername: Customer_A
    Customername: Customer_S
    Customername: Customer_D
    Customername: Customer_F
    TIME:
    JDBC: 0.125 sek
    The Customer.hbm.xml (auto-generated in Eclipse with Middlegen)
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
    <hibernate-mapping>
    <!--
        Created by the Middlegen Hibernate plugin 2.2
        http://boss.bekk.no/boss/middlegen/
        http://www.hibernate.org/
    -->
    <class
        name="hibernate.hibernate.Customer"
        table="CUSTOMER"
        lazy="false"
    >
        <id
            name="uuid"
            type="java.lang.String"
            column="UUID"
        >
            <generator class="assigned" />
        </id>
        <property
            name="name"
            type="java.lang.String"
            column="NAME"
            length="100"
        />
        <property
            name="customerno"
            type="java.lang.Integer"
            column="CUSTOMERNO"
            length="5"
        />
        <property
            name="shortdesc"
            type="java.lang.String"
            column="SHORTDESC"
            length="50"
        />
        <property
            name="longdesc"
            type="java.lang.String"
            column="LONGDESC"
            length="100"
        />
        <property
            name="taxnumber"
            type="java.lang.String"
            column="TAXNUMBER"
            length="50"
        />
        <property
            name="salestaxid"
            type="java.lang.String"
            column="SALESTAXID"
            length="50"
        />
        <property
            name="accountholder"
            type="java.lang.String"
            column="ACCOUNTHOLDER"
            length="50"
        />
        <property
            name="bankaccount"
            type="java.lang.String"
            column="BANKACCOUNT"
            length="50"
        />
        <property
            name="bankcode"
            type="java.lang.String"
            column="BANKCODE"
            length="50"
        />
        <property
            name="bankname"
            type="java.lang.String"
            column="BANKNAME"
            length="50"
        />
        <property
            name="area1text"
            type="java.lang.String"
            column="AREA1TEXT"
            length="50"
        />
        <property
            name="area2text"
            type="java.lang.String"
            column="AREA2TEXT"
            length="50"
        />
        <property
            name="area3text"
            type="java.lang.String"
            column="AREA3TEXT"
            length="50"
        />
        <property
            name="area4text"
            type="java.lang.String"
            column="AREA4TEXT"
            length="50"
        />
        <property
            name="area5text"
            type="java.lang.String"
            column="AREA5TEXT"
            length="50"
        />
        <property
            name="chUuid"
            type="java.lang.String"
            column="CH_UUID"
            length="50"
        />
        <property
            name="reftext1"
            type="java.lang.String"
            column="REFTEXT1"
            length="50"
        />
        <property
            name="reftext2"
            type="java.lang.String"
            column="REFTEXT2"
            length="50"
        />
        <property
            name="reftext3"
            type="java.lang.String"
            column="REFTEXT3"
            length="50"
        />
        <!-- Associations -->
        <!-- bi-directional one-to-many association to Branch -->
        <set
            name="branches"
            lazy="true"
            inverse="true"
           cascade="all"
        >
            <key>
                <column name="CUSTOMER_UUID" />
            </key>
            <one-to-many
                class="hibernate.hibernate.Branch"
            />
        </set>
    </class>
    </hibernate-mapping>So, seems to me like Hibernate is also getting the data from the Branch-Table related to each Customer. Maybe this is the reason, why Hibernate is slower.
    But as you can see in the mapping-File of the customer, I wanted Branches to be lazy loaded.
    Do you have any ideas, why Hibernate is so much slower? Any hints for optimizing that code?
    Do you have any further tricks to optimize Hibernate? Unfortunately I am not allowed to make changes at the database, so I cannot e.g. set indices for optimization.
    However, I�m a Hibernate-Newbie. In fact, I just made this test and was very disappointed about its result, so I didn�t keep on working with Hibernate.
    But maybe you can proof me, that Hibernate is a good choice. If so, do you have any good resources (links, books) that help working with Hibernate in connection with JBOSS, describe how to map n:m relationships, show how to work with large results and so forth?
    Thanx for help,
    egon

  • Urgent: Entity Bean question

    Hi,
    I am using an entity beans to store and load records in a table. When I save records to the table I store them in an order of Primary key ID, but when loading the entity bean this order is not being preserved. Is there any way I can specify what the order (ascending or descending) the entiry bean needs to load records?
    Thanks.

    Dunno what exactly are you asking.
    I mean how are u making bulk entity bean save records?
    What exactly is the purpose ?
    Cheers,
    manjunath

  • A question about entity manager in stateless session bean.

    JSR 220 ejbcore, page 47 : stateless session bean: All business object references of the same interface type for the same stateless session bean have the "same object identity", which is assigned by the container.
    So, if we have two session beans in client code...
    @EJB Cart cart1;
    @EJB Cart cart2;
    then cart1.equals(cart2)==true
    If we declare entity manager in stateless session bean:
    @PersistenceContext( unitName="ds" ,type=PersistenceContextType.TRANSACTION)
    private EntityManager em;If cart1 and cart2 are the same reference, do we have any problem when using the same reference(maybe the same em? ) to get data from db?

    If cart1 and cart2 are the same reference, do we have
    any problem when using the same reference(maybe the
    same em? ) to get data from db?No. In EJB, there is a distinction between the EJB reference and the bean instance.
    Each time you make an invocation on an EJB reference for a stateless session bean,
    the container can choose any instance of that bean's bean class to process the
    invocation. That's true whether you invoke the same reference multiple times or
    two difference references to the same bean.
    Each bean instance is guaranteed to be single-threaded.

Maybe you are looking for