Announcement Announcement Module
Collapse
No announcement yet.
multiple data insert/update single transaction Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • multiple data insert/update single transaction

    I'm studying struts2 + spring + hibernate right now as part of my school project and currently i'm having a hard time trying to get this part to work.
    I'm trying to insert / update multiple entities with a single transaction so that i can commit or rollback the previous data in the batch if something fails while i'm uploading my csv file.

    In my action class in struts I parse the csv data and then pass the list to the service. In the service is where I try to insert/update the data one at a time and then commit them afterwards if no error occurs. During insert/update when an error occurs I want to rollback all of the data that has been inserted / updated to the database. This part i can't seem to make it work. Each time i try to test it with an invalid data in the csv file, the data before the invalid data gets committed to the database.

    Code:
    /**
     * Insert or Update Itemdata Table from a datalist
     */
    public void saveSecBrief(Integer sbID, List lstitemdata ) throws Exception {
    	EntityManager em = this.emf.createEntityManager();
    	EntityTransaction etx = em.getTransaction();
    	etx.begin();
        	
    	try {
    		Itemdata itemdata;
    		String [] nextLine;
    			
    		for (int i = 0; i < lstSecurityBriefing.size(); i ++) {				
    			nextLine = (String [])lstitemdata .get(i);
    				
    			/* Instantiate New Persistence Bean and assign to it*/
    			itemdata = new Itemdata ();
       			itemdata.setSb_upload_id(sbID);
    			itemdata.setItemName(nextLine[0]);
    			itemdata.setItemPrice(nextLine[1]);
    			itemdata.setPurchaseDate(StringConverter.StringToDate(nextLine[2]));
    			itemdata.setExpiryDate(StringConverter.StringToDate(nextLine[3]));
        			
    			if (itemdata.getItemID() == null) {
    		        		em.persist(securitybriefing);
    		        	} else { 
    			        	em.merge(securitybriefing);
    		        }
    		}
    		etx.commit();			
    	} catch (Exception e) {
    		etx.rollback();
    		throw e;
    	} 	
    }
Working...
X