How to implement a SaveOrUpdate general purpose JpaDao method?

Very often I have a new entity that I would like to persist if it is to be considered "not equals" to any other already persisted, otherwise I would like to update the values of the fields that are not to be considered in the @override equals() method defined in the entity. In the new entity the key field is not valorized (very often it is an id @GeneratedValue(strategy = GenerationType.AUTO).
I started to write a method that could be used in these cases ... but I have problems to make it: any help or suggestions?
Here is my first idea:
public abstract class JpaDao<T, PK extends Serializable> implements IDao<T, PK> {
    protected Class<T> persistentClass;
    protected String persistentName = "";
    EntityManager em;
    public JpaDao(EntityManager em) {
        this();
        this.em = em;
    @SuppressWarnings("unchecked")
    public JpaDao() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        // (***) Added from http://www.jroller.com/greenhorn/entry/uberdao_for_jpa
        Annotation[] annotations = persistentClass.getAnnotations();
        for (Annotation annotation : annotations) {
            if (annotation instanceof Entity) {
                persistentName = ((Entity) annotation).name();
                break;
        if (persistentName.equals("")) {
            persistentName = persistentClass.getSimpleName();
        // End (***)
    protected EntityManager getEntityManager() {
        //return JpaUtility.currentEntityManager();
        return this.em;
//HERE IS THE NEW METHOD - ONLY TO GIVE AN IDEA OF WHAT I WOULD LIKE TO DO!!!
//I suppose to have as a parameter the new detached entity that I want to save as new or merge with an already persisted one that is equals to this one (for the point of view of the @override equals() method implemented in the entity itself)
    public T saveOrUpdate(T entity) {
        List<T> entities = listByExample(entity, null, false);
        if (entities.isEmpty()) {
            //no entity found similar to this one
            persist(entity);
        } else {
            //see if ,among the founded persisted entities, there is one to be considered equals to the one passed as parameter
            for (T singleEntity: entities) {
                if (singleEntity.equals(entity)) {
                    ///????? how can I do to update the values of the fields of the singleEntity with the values of the entity parameter and let it persisted?????
        return entity;
    }I'm waiting for suggestions or some link where I can find a method that can do what I need!!!
Kind regards
Enzo
P.S.
Here there are some explanations related to merge that I found and that I think useful ....
//http://docs.jboss.org/hibernate/stable/entitymanager/reference/en/html/objectstate.html
Merging in EJB3 is similar to the saveOrUpdateCopy() method in native Hibernate. However, it is not the same as the saveOrUpdate() method, the given instance is not reattached with the persistence context, but a managed instance is returned by the merge() method.
//http://forum.springsource.org/archive/index.php/t-36064.html
The difference in laymen's terms between JPA's merge and Hibernate's saveOrUpdate is that saveOrUpdate copies the newly managed persistent state onto the object passed into the method, and merge does not.
The merge operation is clever enough to automatically detect whether the merging of the detached instance
has to result in an insert or update.
In other words, you don't have to worry about passing a new instance (and not a detached instance) to merge(),
the entity manager will figure this out for you:
// In the first entity manager
Cat cat = firstEntityManager.find(Cat.class, catID);
// In a higher layer of the application, detached
Cat mate = new Cat();
cat.setMate(mate);
// Later, in a new entity manager
secondEntityManager.merge(cat); // update existing state
secondEntityManager.merge(mate); // save the new instance*/

At the end I wrote the following code:
    public T saveOrUpdate(T entity) {
        List<T> entities = listByExample(entity);
        if (entities.isEmpty()) {
            entity = persist(entity);
        } else {
            //I see if it is equals to the one passed as parameter
            for (T singleEntity : entities) {
                if (singleEntity.equals(entity)) {
                    PK index = getId(singleEntity);
                    setId(entity, index);
                    return merge(entity);
        return entity;
    }In the specific Dao that implements the JpaDao, I need sometime to override the saveOrUpdate method if that entity include an other entity: see the folloving example for a entity Location that has as a member an other entity Address:
public class LocationDao extends JpaDao<Location, Long> {
    @Override
    public Location saveOrUpdate(Location entity) {
        // first of all I see if the Address is already attached:
        if (entity.getAddress().getId() == null) {
            AddressDao addressDao = new AddressDao(em);
            entity.setAddress(addressDao.saveOrUpdate(entity.getAddress()));
    }If someone can suggest me some other better solution let me know!!!
Kind regards
Enzo
Edited by: contini on Jun 1, 2009 6:34 AM

Similar Messages

  • How to implement code with in the destory method

    Created a chat room in Java (JApplet)
    The problems is when leaving the browser window the applet does not
    inform the server, the coding that I have tried to implement is embedded the destory method
    public void destory()
    terminate();
    I am using the right method?
    is there a easy solution?
    terminate method sends a message to the server informing that the client wishes to leave the chat room, on receiving the message the server removes all references to that client. This method is also used in a button event or when the user enters TERMINATE in the text field so I know it works. If any body could give hints or a sun page to look at for information it would be much appreciated.
    Thanks in advance
    Phil

    slight clerical error in spelling thanks,
    but any solution to the problem a part from spelling error in
    message.
    thanks Phil

  • How can we distinguish b/c general purpose and top level containers?

    how can we distinguish b/c general purpose and top level containers?plzzz help me out

    May be this will help u out
    http://www.ictp.trieste.it/~manuals/programming/Java/tutorial/uiswing/components/components_pics.html

  • Having trouble figuring out how to use trigger inputs as a general purpose input.

    I'm trying to use "Trigger 1" as a general purpose input to indicate the status of external circuitry. I can't seem to get the "Read High-Speed Capture Status" to indicate anything. I'm using the "Configure High-Speed Capture" VI with the capture mode set to Inverting Digital Input, and that VI feeds into a Do-While loop which contains the "Read High-Speed Capture Status" VI, which has the Ret Vect set to 0. I see from the online help that the High-Speed Capture function is available on Servo and Closed-Loop stepper systems, which I suppose is to enable the ability to read the position of the encoders. I'm using an open loop stepper system, so are these High-Speed Capture fun
    ctions unavailable even though I'm looking only for status (Trigger 1), and not concerned with reading position? Thanks in advance, Rob.

    Thanks for the answer Ken. I'm going to try a different workaround. The global was too slow, and I think I'll break my subVI into two parts. I'll create a sub that has all the setup stuff in it, then embed the actual "check trigger status" loop in the main VI. The loop contains only 2 or 3 nodes. Too bad LabView works this way. I can see one reason it should, but another larger reason it shouldn't. Wishlist.... Oh, speaking of wishlist, I like the improvements that 6.0 has brought, but one thing still bugs me. There's no way to have LabView remember the place to look for files when it's first started. It defaults to "My Documents", which should be, as all LabView programers know "LabVIEW6\user.lib" (or whatever). Of course, once th
    ere, LabView remembers for that session. Next time it's started, back to "My Documents" again. How 'bout fixing the "Options", "Path" settings so that it will actually remember the path set? Am I missing something here, or does it have anything to do with the fact that we're using Windows 98? My buddy's using NT, and his works the same. Is there a way around this? TIA, Rob.

  • How to create general purpose database using dbca

    Hi,
    I have installed oracle 10g on AIX .
    and now i have to create a database/instance for the firsttime whch must to be general using dbca.
    I want to create database silently. could any one please tell me the command to create a database silently

    Hello,
    So as to do a completely silent installation you may use a responsefile as follow:
    $ORACLE_HOME/bin/dbca -silent -cloneTemplate *<General Purpose option>* -datafileDestination */datafilepath* -responseFile */local_dir/dbca.rsp*Where dbca.rsp is a response file template that you may edit so as to supply administrative password,...
    Else, about the reason why your command got stuck. You may check the exact options with the statement below:
    dbca -hIt may change from one release to another.
    Hope this help.
    Best regards,
    Jean-Valentin

  • How to implement a delay of usec (6025E board)

    I want to implement a delay of usec(say 0.5usec) however the 2 24bit general purpose counter was already used up.
    how can i implement the 0.5usec delay without using the 24bit counter?
    Thks & best regards
    lyn

    Hi,
    I am not sure that this is possible; you can implement software delays, but to within 1ms resolution. For the usec resolution, you definitely need a counter.
    Regards,
    RamziH.

  • How to implement parent entity for core data

    Hi there.
    I am starting a document-based Core Data application (Cocoa) and developed the following data model;
    The 'invoice' entity is a parent entity of 'items', because ideally I would want there to be many items for each invoice. I guess my first point here is - is what I am trying to do going to be achieved using this method?
    If so, I have been trying several ways in Interface Builder to sort out how to implement this structure with cocoa bindings. I have made a Core Data app before, just with one entity. So this time, I have two separate instances of NSArrayController's connected to tables with relevant columns. I can add new 'invoice' entities fine, but I can't get corresponding 'items' to add.
    I tried setting the Managed Object Context of the 'item' NSArrayController to this;
    I thought this would resolve the issue, but I still have found no resolution to the problem.
    If anyone done something similar to this, I'd appreciate any help
    Thanks in advance,
    Ricky.

    Second, when you create a Core Data Document Based application, XCode generates the MyDocument class, derivating from NSPersistentDocument. This class is dedicated to maintain the Managed Object Model and the Managed Object Context of each document of your application.
    There is only one Context and generally one Model for each Document.
    In Interface Builder, the Managed Object Context must be bound to the managedObjectContext of the MyDocument instance: it's the File's owner of the myDocument.xib Nib file.
    It's not the case in your Nib File where the Managed Object Context is bound to the invoiceID of the Invoice Controller.
    It's difficult to help you without an overall knowledge of your application, perhaps could you create an InvoiceItem Controller and bind its Content Set to the relationship of your invoice.

  • How to implement Tax reporting in HFM

    Hi
    friend please help me to find, How to implement Tax reporting in HFM
    Thanks
    Mayank

    This applies to all of your questions.
    Print out the manuals and start reading. You can find them on any machine that has HFM installed or here on the Oracle site. After that, if you still have general questions, try searching the Oracle site. If you have a specific question, feel free to post it here.

  • How to implement autocomplete?

    Hello,
    I have a String array with strings in non-alphabethical order.
    I would like to implement autocomplete (just like in IE address line) on a JTextField.
    I guess I'll need to put some listener on textfield, but which? And how to handle array - sort it before use? Any other possibilities?

    Well, first you'd need something to compare the String being typed in to, so that you know what the user might be trying to type. Then, I guess you'd need a KeyListener on text field, so each time a key is pressed, you run a search and return all the possible Strings that could match it.
    I'd be a little lost as to how to implement the drop-down list like IE (or Windows in general) has to handle auto-complete. The other way to handle it would be to have the word fill itself into the textbox as you type, leaving the guessed part highlighted so you can continue to type, and continue to get suggestions. This approach seems a bit easier, and could be handled fairly easily.

  • How to implement a conversion rule in KC7R (External Data transfer-Tool)

    Hi,
    I am familiar with programming conversion rules in ABAP in the LSMW and IS-U Migration workbench.
    Unfortunately we have to work with EDT (transaction KCLJ).
    I need to implement a simple conversion rule: migration file has the external BP number BPEXT and I must retrieve the internalone (PARTNER) for the migration program.
    So I must implement a short ABAP code (select single * from BUT000 ...).
    Now I see that in KC7R you can use constants and conversion rules. There are also "General Ruels" and "conversion routines".
    Can someone explain how to implement this simple ABAP conversion rule in KC7R giving a short example?
    This would be great.
    EDT is the workst of all SAP Standard Migration Tools I have seen.....
    Kind regards,
    Thomas

    Thomas,
    Coud you please share your findings as I am now in a similar to your original post.
    ie I too would like to know how to code convesions for use within the transfer rules used by KCLJ.
    Kind Regards,
    Hiten Mistry.

  • How to implement FI-CA module in BI

    Hi Experts,
                      I am doing SAP BI project on FI-CA module.I have no idea about this module.
                please guide me how to implement this module
    thanks in Advance....youwill  surley get  points.
    regards
    ABHI

    Abhishek,
    Forum rules clearly state that basic searches should be performed before posting a question, and then post only questions about specific issues.  These forums are unfortunately ill-suited for teaching a novice how to implement a complex SAP module.
    Standard SAP Help FI-CA
    http://help.sap.com/erp2005_ehp_06/helpdata/EN/73/834f3e58717937e10000000a114084/frameset.htm
    Available training
    https://training3.sap.com/us/en/course/ac240-contract-accounts-receivable-and-payable-classroom-095-us-en/
    The BPE General forum does not deal with the topic you mention.  You will have better luck posting to an FI or BW related forum. 
    Basic FI Forum
    SAP ERP Financials
    Basic BW Forum
    SAP Business Warehouse
    Best Regards & Good Luck,
    DB49

  • How to implement User Exit in APO?

    Hello All,
    I am not sure how to use user exits. I was wondering if anyone can help me understand how to implement any user exit? Is there any T.Code where you do that? or ABAP coding is required? Also how different is BAdi from User exits?
    Any advice is welcome.
    Thanks,
    Sanju

    Hi Sanju,
        Check this link.
    http://www.sap-img.com/abap/difference-between-badi-and-user-exits.htm
    BADI or user exit, I don't think it is a choice between the two. Both serve the same purpose, add some custom logic to the standard logic. It depends on your requirement, the point when the user exit or BADI is called, information that is available to you in that user exit/BADI and information that you can change in that user exit/BADI. There is no difference in implementing the User Exit in APO or R/3.
    Regards,
    Siva.

  • How to implement command pattern into BC4J framework?

    How to implement command pattern into BC4J framework, Is BC4J just only suport AIDU(insert,update,delete,query) function? Could it support execute function like salary caculation in HR system or posting in GL(general ledger) system? May I create a java object named salaryCalc which use view objects to get the salary by employee and then write it to database?
    Thanks.

    BC4J makes it easy to support the command pattern, right out of the box.
    You can write a custom method on your application module class, then visit the application module wizard and see the "Client Methods" tab to select which custom methods should be exposed for invocation as task-specific commands by clients.
    BC4J is not only for Insert,Update,Delete style applications. It is a complete application framework that automates most of the typical things you need to do while building J2EE applications. You can have a read of my Simplifying J2EE and EJB Development Using BC4J whitepaper to read up on an overview of all the basic J2EE design patterns that the framework implements for you.
    Let us know if you have more specific questions on how to put the framework into practice.

  • Reg - how to find the purpose of methods in a class

    hi everyone,
               can u plz help me with how to find the purpose of methods in a class???????
    a description abt the methods in a class??????
                        thx in advance,
    regards,
    balaji.s

    Hi Balaji
    Pls find some stuff.
    reward pts if help.
    The following statements define the structure of a class:
    ·        A class contains components
    ·        Each component is assigned to a visibility section
    ·        Classes implement methods
    The following sections describe the structure of classes in more detail.
    Class Components
    The components of a class make up its contents. All components are declared in the declaration part of the class. The components define the attributes of the objects in a class. When you define the class, each component is assigned to one of the three visibility sections, which define the external interface of the class. All of the components of a class are visible within the class. All components are in the same namespace. This means that all components of the class must have names that are unique within the class.
    There are two kinds of components in a class - those that exist separately for each object in the class, and those that exist only once for the whole class, regardless of the number of instances. Instance-specific components are known as instance components. Components that are not instance-specific are called static components.
    In ABAP Objects, classes can define the following components. Since all components that you can declare in classes can also be declared in interfaces, the following descriptions apply equally to interfaces.
    Attributes
    Attributes are internal data fields within a class that can have any ABAP data type. The state of an object is determined by the contents of its attributes. One kind of attribute is the reference variable. Reference variables allow you to create and address objects. Reference variables can be defined in classes, allowing you to access objects from within a class.
    Instance Attributes
    The contents of instance attributes define the instance-specific state of an object. You declare them using the DATAstatement.
    Static Attributes
    The contents of static attributes define the state of the class that is valid for all instances of the class. Static attributes exist once for each class. You declare them using the CLASS-DATA statement. They are accessible for the entire runtime of the class.
    All of the objects in a class can access its static attributes. If you change a static attribute in an object, the change is visible in all other objects in the class.
    The technical properties of instance attributes belong to the static properties of a class. It is therefore possible to refer in a LIKE addition to the visible attributes of a class – through the class component selector or through reference variables, without prior creation of an object.
    Methods
    Methods are internal procedures in a class that define the behavior of an object. They can access all of the attributes of a class. This allows them to change the data content of an object. They also have a parameter interface, with which users can supply them with values when calling them, and receive values back from them The private attributes of a class can only be changed by methods in the same class.
    The definition and parameter interface of a method is similar to that of function modules. You define a method meth in the definition part of a class and implement it in the implementation part using the following processing block:
    METHOD meth.
    ENDMETHOD.
    You can declare local data types and objects in methods in the same way as in other ABAP procedures (subroutines and function modules). You call methods using the CALL METHOD statement.
    Instance Methods
    You declare instance methods using the METHODSstatement. They can access all of the attributes of a class, and can trigger all of the events of the class.
    Static Methods
    You declare static methods using the CLASS-METHODSstatement. They can only access static attributes and trigger static events.
    Special Methods
    As well as normal methods, which you call using CALL METHOD, there are two special methods called constructor and class_constructor that are automatically called when you create an object or when you first access the components of a class.
    reward pts if help.
    deepanker

  • Ymenu - Interfaces - Post Document (General Purpose) -- FBB1

    Hi,
    I tried to perform as per below:
    I went to ymenu - -> Interfaces --> Post Document (General Purpose) -- FBB1
    After that in the Source file, i selected the file that i would like to upload.
    Follow by click on the execute button.
    Can i know after i have uploaded to the SAP system then how am i going to display or review back the uploaded data in the SAP System. (The data is in Excel)
    Which transaction code should i use?
    Thanks.
    Best Regards,
    Joo

    Hi Gimmo,
    Thanks for the links.
    I went to  "Reports for evaluating transferred data - RFBELS00 "
    Then i enter RFBELS00 into the SAP system but this Transaction code does not exist?
    i went to SE16, i think RFBELS00 is not a table rite?
    Can i know how am i going to display it?
    Thanks.
    Best Regards,
    Joo

Maybe you are looking for

  • Error in Updating Billing Docs

    Hi Gurus, When i'm updating the some billing docts in VBOF,  the system thros the "No correction due to value change" error. Can u tell me what is the problem? cheers, Sumith

  • Set and get parameter id

    Hi, I need to store one variable value and I need to retrieve the same variable value in same program. For this I have written set and get parameter ids in the same program. It is working fine but if I log off the system and if I logon the system it

  • Importing word file into InDesign problems

    I use the following code: myText.Place("C:\Development\memoTest Assignments\temp.docx"), the doc file will become Objective Experience Education Statement although original doc file is Objective Experience Education Statement It seems it will cause b

  • Outlook 2007 contact synch problems with iCloud

    Running into difficulties synching iCloud 1.0.1 contacts with Outlook 2007.  It freezes/crashes outlook quite regularly. The contacts properly synched the the first time but now I'm getting "Couldn't save changes to x items" when Outlook tries to syn

  • ABAP program using infotypes and FM

    Hi all, I have to work on  abap -HR module,  which is using infotypes, BDC, FM, internal tables.. As  I am new in this  and no more idea. So can you please share some document  and some  simple program, so that I can understand the HR modules with re