CustomerFactory.java :  » Database-ORM » ProjectJulp » org » julp » examples » Java Open Source

Java Open Source » Database ORM » ProjectJulp 
ProjectJulp » org » julp » examples » CustomerFactory.java
package org.julp.examples;

import java.util.*;
import org.julp.*;
import org.julp.misc.search.*;
import java.sql.*;

public class CustomerFactory extends org.julp.DomainObjectFactory implements java.io.Serializable, Cloneable{
    
    protected Properties sqlMap = null;
    
    public CustomerFactory() {
        /* IT IS NOT NECESSARY TO LOAD MAPPINGS THIS WAY, COULD BE ANYTHING: XML, JNDI, DATABASE, ETC... */
        sqlMap = loadMappings("Customer.sql");
        initFactory();
        setRequestor(Customer.class);
    }
    
     protected void initFactory(){
        try{
            BasicDataSourceImpl ds = new BasicDataSourceImpl();
            ds.setDriverName("org.hsqldb.jdbcDriver");
            ds.setDbURL("jdbc:hsqldb:hsql://localhost");
            ds.setUserName("sa");
            ds.setPassword("");           
            this.dbServices = new DBServices();
            dbServices.setDataSource(ds); 
            setMapping(loadMappings("Customer.properties"));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    
    public Properties loadMappings(String path){
        java.io.InputStream inStream = null;
        Properties props = new Properties();
        try{
            inStream = this.getClass().getResourceAsStream(path);
            props.load(inStream);
        }catch(java.io.IOException ioe){
            throw new RuntimeException(ioe);
        }finally{
            try{
                inStream.close();
            }catch(java.io.IOException ioe){
                throw new RuntimeException(ioe);
            }
        }
        return props;
    }
    
    public void selectAs(){
        System.out.println("\n======================= this is an example of using some methods to populate collections ===========================\n");
        try{
            setMapping(loadMappings("Customer.properties"));
            String sql = sqlMap.getProperty("findAllCustomersWithPhone");
            System.out.println("============== as ValueObjects list (first column value and second column display) ==================");
            List list = dbServices.getResultAsValueObjectList(sql);
            System.out.println(list);
            System.out.println("============== as Vector of Vectors ==================");
            Vector vector1 = dbServices.getResultAsVector(sql);
            System.out.println(vector1);
            System.out.println("============== as Map of Lists (key=column name, value=list of values for the column) ==================");
            Map map = dbServices.getResultAsMap(sql);
            System.out.println(map);
            //System.out.println("============== ==================");
            //Vector vector2 = dbServices.getResultAsVector(sql);
            //System.out.println(vector2);
            System.out.println("============== as DataHolders array ==================");
            
            DataHolder[] dataHolder = dbServices.getResultAsDataHoldersArray(sql, false);
            for (int i = 0;i < dataHolder.length;i++){
                System.out.println(dataHolder[i]);
            }
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            try{
                dbServices.release(true);
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }
    
    public void inClause(){
        System.out.println("\n======================= this is an example of using 'IN' CLAUSE \n======================= and using SELECT with number of parameters \n======================= more than DBMS can except (like more then 254 in Oracle) to populate objectList ===========================\n");
        try{
            dbServices.setMaxNumberOfParams(3);
            dbServices.setPlaceHolder(":#"); // could be any String
            //dbServices.setDebug(true);
            dbServices.setCacheStatements(true);
            setRequestor(Customer.class);
            setMapping(loadMappings("Customer.properties"));
            
            List argsList = new ArrayList();
            String sql = sqlMap.getProperty("inClause");
            
            //List city = new ArrayList();
            //city.add("City1");
            //city.add("City2");
            //city.add("City3");
            //
            //List phone = new ArrayList();
            //phone.add("1111111111");
            //phone.add("2222222222");
            
            List custId = new ArrayList();
            custId.add(new Integer(0));
            custId.add(new Integer(1));
            custId.add(new Integer(2));
            custId.add(new Integer(3));
            custId.add(new Integer(4));
            custId.add(new Integer(5));
            custId.add(new Integer(6));
            custId.add(new Integer(7));
            
            argsList.add("John Doh");
            //argsList.add(city);
            //argsList.add(phone);
            argsList.add(custId);
            
            load(dbServices.getResultSets(sql, argsList));                        
            
            Iterator it1 = getObjectList().iterator();
            while(it1.hasNext()){
                System.out.println(it1.next());
            }
            dbServices.release(false);
            System.out.println("==================================");
            
            List list = dbServices.getResultsAsDataHoldersList(sql, argsList, false);
            
            Iterator it2 = list.iterator();
            while(it2.hasNext()){
                System.out.println(it2.next());
            }            
        }catch(Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally{
            try{
                dbServices.release(true);
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }
    
    public int findAllCustomers(){
        int records = 0;
        try{
            String sql = sqlMap.getProperty("findAllCustomers");
            records = this.load(this.dbServices.getResultSet(sql));
            printAllCustomers();
        }catch (SQLException sqle){
            throw new RuntimeException(sqle);
        }
        return records;
    }
    
    public int findAllCustomersWithPhone(){
        System.out.println("\n======================= this is an example of using inheritance ===========================\n");
        this.setRequestor(CustomerWithPhone.class);
        
        setMapping(loadMappings("CustomersWithPhone.properties"));
        
        /*or:  comment line above: setMapping(loadMappings("CustomersWithPhone.properties"));
              and uncomment two lines below */
        
        /*
        setMapping(loadMappings("Customer.properties"));
        this.mapping.put("CUSTOMER.PHONE", "phone");
         */
        
        int records = 0;
        try{
            records = this.load(this.dbServices.getResultSet(sqlMap.getProperty("findAllCustomersWithPhone")));
            printAllCustomers();
        }catch (SQLException sqle){
            throw new RuntimeException(sqle);
        }
        return records;
    }
    
    public void createAndStoreCustomers(){
        System.out.println("\n======================= this is an example of creating and storing objects (INSERT & UPDATE) ===========================\n");
        this.setRequestor(CustomerWithPhone.class);
        setMapping(loadMappings("CustomersWithPhone.properties"));
        this.getDBServices().setCacheStatements(true);
        int records = findAllCustomers();
        CustomerWithPhone customerWithPhone = new CustomerWithPhone();
        // this is NOT proper way to genarate id
        customerWithPhone.setCustomerId(new Integer(records + 1));
        customerWithPhone.setFirstName("Joe");
        customerWithPhone.setLastName("Doe");
        customerWithPhone.setStreet("Main st.");
        customerWithPhone.setCity("SomeTown");
        customerWithPhone.setPhone("7777777777");
        
        this.create(customerWithPhone);
        System.out.println("\ncreated customer: " + customerWithPhone + "\n");
        
/*       another way:
         customerWithPhone.create();
         customerWithPhone.setObjectId(this.getNextObjectId());
         this.getObjectList().add(product);
         or:
         customerWithPhone.create();
         this.setObject(customerWithPhone);
 */
        
        ListIterator li = this.objectList.listIterator();
        while (li.hasNext()){
            CustomerWithPhone customer = (CustomerWithPhone) li.next();
            String lastName = customer.getLastName();
            if (lastName.equals("Miller")){
                customer.setPhone("8888888888");
                customer.store();
            }
        }
        
        System.out.println("\n======================= this is after data modifications ===========================\n");
        printAllCustomers();
        
        try{
            this.dbServices.beginTran();
            boolean success = this.writeData();
            Throwable t = this.getWhatIsWrong();
            if (t != null){
                throw t;
            }
            if (success){
                this.dbServices.commitTran();
            }else{
                throw new SQLException("Data modification: failed");
            }
            this.synchronizePersistentState();
        }catch (Throwable t){
            try{
                this.dbServices.rollbackTran();
            }catch (SQLException sqle){
                sqle.printStackTrace();
                throw new RuntimeException(sqle);
            }
            t.printStackTrace();
        }finally{
            try{
                this.dbServices.release(true);
            }catch (SQLException sqle){
                sqle.printStackTrace();
                throw new RuntimeException(sqle);
            }
        }
        
        System.out.println("\n======================= this is after COMMIT & synchronizePersistentState() or after ROLLBACK ===========================\n");
        printAllCustomers();
    }
    
    public void findCustomer(){
        System.out.println("\n======================= this is an example of using Criteria  ===========================\n");
        setMapping(loadMappings("Customer.properties"));
        this.populateMetaData();
        List holders = new ArrayList(2);
        SearchCriteriaHolder searchCriteriaHolder1 = new SearchCriteriaHolder();
        searchCriteriaHolder1.setFieldName("lastName");
        searchCriteriaHolder1.setOperator(SearchCriteriaHolder.LIKE);
        searchCriteriaHolder1.setFunctions("UPPER(${})"); //UPPER(col_name)
        searchCriteriaHolder1.setSearchValue("MI%");
        searchCriteriaHolder1.setBooleanCondition(SearchCriteriaHolder.OR);
        holders.add(searchCriteriaHolder1);
        SearchCriteriaHolder searchCriteriaHolder2 = new SearchCriteriaHolder();
        searchCriteriaHolder2.setFieldName("lastName");
        searchCriteriaHolder2.setOperator(SearchCriteriaHolder.LIKE);
        searchCriteriaHolder2.setFunctions("UPPER(${})");
        searchCriteriaHolder2.setSearchValue("S%");
        holders.add(searchCriteriaHolder2);
        CustomerCriteria criteria = new CustomerCriteria();
        criteria.setMetaData(this.metaData);
        criteria.setSearchCriteriaHolders(holders);
        criteria.buildCriteria();
        String select = this.sqlMap.getProperty("findAllCustomers");
        criteria.setSelect(select);
        String sql = criteria.getQuery();
        Collection params = criteria.getArguments();
        
        try{
            this.dbServices.setDebug(true);
            this.load(this.dbServices.getResultSet(sql, params));
        }catch (SQLException sqle){
            throw new RuntimeException(sqle);
        }
        printAllCustomers();
    }
    
    protected void printAllCustomers(){
        List products = this.getObjectList();
        Iterator iter = products.iterator();
        while (iter.hasNext()){
            Customer customer = (Customer) iter.next();
            System.out.println(customer);
        }
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.