JDBCPreparedStatementUtilities.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */
  20. package org.openspcoop2.generic_project.dao.jdbc.utils;

  21. import java.sql.Connection;
  22. import java.sql.PreparedStatement;
  23. import java.sql.ResultSet;
  24. import java.sql.SQLException;
  25. import java.sql.Statement;
  26. import java.util.ArrayList;
  27. import java.util.List;

  28. import org.slf4j.Logger;
  29. import org.openspcoop2.generic_project.beans.IModel;
  30. import org.openspcoop2.generic_project.exception.MultipleResultException;
  31. import org.openspcoop2.generic_project.exception.NotFoundException;
  32. import org.openspcoop2.generic_project.exception.ServiceException;
  33. import org.openspcoop2.utils.TipiDatabase;
  34. import org.openspcoop2.utils.jdbc.IKeyGenerator;
  35. import org.openspcoop2.utils.jdbc.IKeyGeneratorObject;
  36. import org.openspcoop2.utils.jdbc.JDBCAdapterException;
  37. import org.openspcoop2.utils.jdbc.KeyGeneratorException;
  38. import org.openspcoop2.utils.jdbc.KeyGeneratorFactory;
  39. import org.openspcoop2.utils.sql.ISQLQueryObject;
  40. import org.openspcoop2.utils.sql.SQLQueryObjectException;

  41. /**
  42.  * JDBCPreparedStatementUtilities
  43.  *
  44.  * @author Poli Andrea (apoli@link.it)
  45.  * @author $Author$
  46.  * @version $Rev$, $Date$
  47.  */
  48. public class JDBCPreparedStatementUtilities {

  49.     private Logger log;
  50.     private Connection connection;
  51.     private JDBCSqlLogger sqlLogger;
  52.     private TipiDatabase tipoDatabase = null;
  53.     private GenericJDBCParameterUtilities jdbcParameterUtilities = null;
  54.     private Integer queryTimeout = null;
  55.    
  56.     public JDBCPreparedStatementUtilities(TipiDatabase tipoDatabase,Logger log,Connection connection) throws SQLQueryObjectException, JDBCAdapterException{
  57.         this(tipoDatabase, log, connection, null);
  58.     }
  59.     public JDBCPreparedStatementUtilities(TipiDatabase tipoDatabase,Logger log,Connection connection,Integer queryTimeout) throws SQLQueryObjectException, JDBCAdapterException{
  60.         this.log = log;
  61.         this.connection = connection;
  62.         this.sqlLogger = new JDBCSqlLogger(this.log);
  63.         this.tipoDatabase = tipoDatabase;
  64.         this.jdbcParameterUtilities = new GenericJDBCParameterUtilities(this.tipoDatabase);
  65.         this.queryTimeout = queryTimeout;
  66.     }
  67.    
  68.     private PreparedStatement _createPreparedStatement(String sql) throws SQLException {
  69.         return this._createPreparedStatement(sql, null);
  70.     }
  71.     private PreparedStatement _createPreparedStatement(String sql, Integer params) throws SQLException {
  72.         PreparedStatement p = null;
  73.         if(params!=null) {
  74.             p = this.connection.prepareStatement(sql,params);
  75.         }
  76.         else {
  77.             p = this.connection.prepareStatement(sql);
  78.         }
  79.         if(this.queryTimeout!=null && this.queryTimeout>0) {
  80.             p.setQueryTimeout(this.queryTimeout.intValue());
  81.         }
  82.         return p;
  83.     }
  84.    
  85.     public long insertAndReturnGeneratedKey(ISQLQueryObject sqlQueryObject,IKeyGeneratorObject object,boolean showSql,JDBCObject ... params) throws KeyGeneratorException{

  86.         PreparedStatement pstmt = null;
  87.         try{
  88.            
  89.             // KeyGenerator
  90.             IKeyGenerator keyGenerator = KeyGeneratorFactory.createKeyGeneratorFactory(this.tipoDatabase.getNome(), this.connection, object);

  91.             // Parametri di insert
  92.             List<JDBCObject> p = new ArrayList<>();
  93.             if(params!=null){
  94.                 for (int i = 0; i < params.length; i++) {
  95.                     p.add(params[i]);
  96.                 }
  97.             }
  98.             if(keyGenerator.isReturnGeneratedKeySupported()==false){
  99.                 JDBCObject jdbcObject = new JDBCObject(keyGenerator.generateKey(),Long.class);
  100.                 p.add(jdbcObject);
  101.             }
  102.             JDBCObject[]paramsWithId = null;
  103.             if(p.size()>0)
  104.                 paramsWithId = p.toArray(new JDBCObject[1]);
  105.            
  106.             // Query di insert
  107.             sqlQueryObject.addInsertTable(object.getTable());
  108.             if(keyGenerator.isReturnGeneratedKeySupported()==false){
  109.                 sqlQueryObject.addInsertField(keyGenerator.getColunmKeyName(), "?");
  110.             }
  111.             String insertString = sqlQueryObject.createSQLInsert();
  112.             if(showSql){
  113.                 this.sqlLogger.infoSql(insertString, paramsWithId);
  114.             }
  115.            
  116.             // Eseguo Prepared Statement
  117.             if(keyGenerator.isReturnGeneratedKeySupported()){
  118.                 pstmt = _createPreparedStatement(insertString,Statement.RETURN_GENERATED_KEYS);
  119.             }else{
  120.                 pstmt = _createPreparedStatement(insertString);
  121.             }
  122.             this.jdbcParameterUtilities.setParameters(pstmt, paramsWithId);
  123.             pstmt.executeUpdate();

  124.            
  125.             // Ritorno id generato
  126.             return keyGenerator.getReturnGeneratedKey(pstmt);

  127.         }catch(Exception e){
  128.             throw new KeyGeneratorException ("insertAndReturnGeneratedKey failed: "+e.getMessage(),e);
  129.         }finally{
  130.             try{
  131.                 if(pstmt!=null)
  132.                     pstmt.close();
  133.             }catch(Exception eClose){
  134.                 // close
  135.             }
  136.         }
  137.     }
  138.    
  139.     public boolean execute(String sql,boolean showSql,JDBCObject ... params ) throws ServiceException{
  140.        
  141.         PreparedStatement pstmt = null;
  142.         try{
  143.            
  144.             if(showSql)
  145.                 this.sqlLogger.infoSql(sql, params);
  146.            
  147.             pstmt = _createPreparedStatement(sql);
  148.             this.jdbcParameterUtilities.setParameters(pstmt, params);
  149.            
  150.             return pstmt.execute();
  151.            
  152.         }catch(Exception e){
  153.             throw new ServiceException(e.getMessage(),e);
  154.         }
  155.         finally{
  156.             try{
  157.                 if(pstmt!=null){
  158.                     pstmt.close();
  159.                 }
  160.             }catch(Exception eClose){
  161.                 // close
  162.             }
  163.         }
  164.     }
  165.    
  166.     public int executeUpdate(String sql,boolean showSql,JDBCObject ... params ) throws ServiceException{
  167.        
  168.         PreparedStatement pstmt = null;
  169.         try{
  170.            
  171.             if(showSql)
  172.                 this.sqlLogger.infoSql(sql, params);
  173.            
  174.             pstmt = _createPreparedStatement(sql);
  175.             this.jdbcParameterUtilities.setParameters(pstmt, params);
  176.            
  177.             return pstmt.executeUpdate();
  178.            
  179.         }catch(Exception e){
  180.             throw new ServiceException(e.getMessage(),e);
  181.         }
  182.         finally{
  183.             try{
  184.                 if(pstmt!=null){
  185.                     pstmt.close();
  186.                 }
  187.             }catch(Exception eClose){
  188.                 // close
  189.             }
  190.         }
  191.     }
  192.    
  193.     public Object executeQuerySingleResult(String sql,boolean showSql,IModel<?> model, IJDBCFetch fetch, JDBCObject ... params ) throws ServiceException, MultipleResultException, NotFoundException{
  194.         List<Object> list = this.executeQuery(sql, showSql, model, fetch, params);
  195.         if(list.size()==1){
  196.             Object o = list.get(0);
  197.             if(o!=null){
  198.                 return o;
  199.             }
  200.             else{
  201.                 throw new NotFoundException("Not found");
  202.             }
  203.         }
  204.         else if(list.size()<=0){
  205.             throw new NotFoundException("Not found");
  206.         }
  207.         else{
  208.             throw new MultipleResultException("More than one result found (result: "+list.size()+")");
  209.         }
  210.     }
  211.    
  212.     public List<Object> executeQuery(String sql,boolean showSql,IModel<?> model, IJDBCFetch fetch, JDBCObject ... params ) throws ServiceException{
  213.        
  214.         PreparedStatement pstmt = null;
  215.         ResultSet rs = null;
  216.         List<Object> lista = new ArrayList<>();
  217.         try{
  218.            
  219.             if(showSql)
  220.                 this.sqlLogger.infoSql(sql, params);
  221.            
  222.             pstmt = _createPreparedStatement(sql);
  223.             this.jdbcParameterUtilities.setParameters(pstmt, params);
  224.            
  225.             rs =  pstmt.executeQuery();
  226.             while(rs.next()){
  227.                 lista.add(fetch.fetch(this.tipoDatabase,model,rs));
  228.             }
  229.             return lista;
  230.            
  231.         }catch(Exception e){
  232.             throw new ServiceException(e.getMessage(),e);
  233.         }
  234.         finally{
  235.             try{
  236.                 if(rs!=null){
  237.                     rs.close();
  238.                 }
  239.             }catch(Exception eClose){}
  240.             try{
  241.                 if(pstmt!=null){
  242.                     pstmt.close();
  243.                 }
  244.             }catch(Exception eClose){
  245.                 // close
  246.             }
  247.         }
  248.     }
  249.    
  250.     public Object executeQuerySingleResult(String sql,boolean showSql,Class<?> returnType,JDBCObject ... params ) throws NotFoundException, ServiceException, MultipleResultException{
  251.         List<Object> list = this.executeQuery(sql, showSql, returnType, params);
  252.         if(list.size()==1){
  253.             Object o = list.get(0);
  254.             if(o!=null){
  255.                 return o;
  256.             }
  257.             else{
  258.                 throw new NotFoundException("Not found");
  259.             }
  260.         }
  261.         else if(list.size()<=0){
  262.             throw new NotFoundException("Not found");
  263.         }
  264.         else{
  265.             throw new MultipleResultException("More than one result found (result: "+list.size()+")");
  266.         }
  267.     }
  268.     public List<Object> executeQuery(String sql,boolean showSql,Class<?> returnType,JDBCObject ... params ) throws ServiceException{
  269.        
  270.         PreparedStatement pstmt = null;
  271.         ResultSet rs = null;
  272.         List<Object> lista = new ArrayList<>();
  273.         try{
  274.            
  275.             if(showSql)
  276.                 this.sqlLogger.infoSql(sql, params);
  277.            
  278.             pstmt = _createPreparedStatement(sql);
  279.             this.jdbcParameterUtilities.setParameters(pstmt, params);
  280.            
  281.             rs =  pstmt.executeQuery();
  282.             while(rs.next()){
  283.                 lista.add(this.jdbcParameterUtilities.readParameter(rs, 1, returnType));
  284.             }
  285.             return lista;
  286.            
  287.         }catch(Exception e){
  288.             throw new ServiceException(e.getMessage(),e);
  289.         }
  290.         finally{
  291.             try{
  292.                 if(rs!=null){
  293.                     rs.close();
  294.                 }
  295.             }catch(Exception eClose){}
  296.             try{
  297.                 if(pstmt!=null){
  298.                     pstmt.close();
  299.                 }
  300.             }catch(Exception eClose){
  301.                 // close
  302.             }
  303.         }
  304.     }
  305.    
  306.     public List<Object> executeQuerySingleResult(String sql,boolean showSql,List<Class<?>> returnType,JDBCObject ... params ) throws ServiceException, MultipleResultException{
  307.         List<List<Object>> list = this.executeQuery(sql, showSql, returnType, params);
  308.         if(list.size()==1){
  309.             return list.get(0);
  310.         }
  311.         else if(list.size()<=0){
  312.             return new ArrayList<>();
  313.         }
  314.         else{
  315.             throw new MultipleResultException("More than one result found (result: "+list.size()+")");
  316.         }
  317.     }
  318.     public List<List<Object>> executeQuery(String sql,boolean showSql,List<Class<?>> returnType,JDBCObject ... params ) throws ServiceException{
  319.        
  320.         PreparedStatement pstmt = null;
  321.         ResultSet rs = null;
  322.         List<List<Object>> lista = new ArrayList<List<Object>>();
  323.         try{
  324.            
  325.             if(showSql)
  326.                 this.sqlLogger.infoSql(sql, params);
  327.            
  328.             pstmt = _createPreparedStatement(sql);
  329.             this.jdbcParameterUtilities.setParameters(pstmt, params);
  330.            
  331.             rs =  pstmt.executeQuery();
  332.             while(rs.next()){
  333.                 List<Object> result = new ArrayList<>();
  334.                 for (int i = 0; i < returnType.size(); i++) {
  335.                     result.add(this.jdbcParameterUtilities.readParameter(rs, (i+1), returnType.get(i)));    
  336.                 }
  337.                 lista.add(result);
  338.             }
  339.             return lista;
  340.            
  341.         }catch(Exception e){
  342.             throw new ServiceException(e.getMessage(),e);
  343.         }
  344.         finally{
  345.             try{
  346.                 if(rs!=null){
  347.                     rs.close();
  348.                 }
  349.             }catch(Exception eClose){}
  350.             try{
  351.                 if(pstmt!=null){
  352.                     pstmt.close();
  353.                 }
  354.             }catch(Exception eClose){
  355.                 // close
  356.             }
  357.         }
  358.     }
  359.    
  360.     public boolean exists(String sql,boolean showSql,JDBCObject ... params ) throws ServiceException{
  361.        
  362.         PreparedStatement pstmt = null;
  363.         ResultSet rs = null;
  364.         try{
  365.            
  366.             if(showSql)
  367.                 this.sqlLogger.infoSql(sql, params);
  368.            
  369.             pstmt = _createPreparedStatement(sql);
  370.             this.jdbcParameterUtilities.setParameters(pstmt, params);
  371.            
  372.             rs =  pstmt.executeQuery();
  373.             return rs.next();
  374.            
  375.         }catch(Exception e){
  376.             throw new ServiceException(e.getMessage(),e);
  377.         }
  378.         finally{
  379.             try{
  380.                 if(rs!=null){
  381.                     rs.close();
  382.                 }
  383.             }catch(Exception eClose){}
  384.             try{
  385.                 if(pstmt!=null){
  386.                     pstmt.close();
  387.                 }
  388.             }catch(Exception eClose){
  389.                 // close
  390.             }
  391.         }
  392.     }
  393.    
  394.     public boolean deleteById(String sql,boolean showSql,JDBCObject ... params ) throws ServiceException{
  395.        
  396.         PreparedStatement pstmt = null;
  397.         ResultSet rs = null;
  398.         try{
  399.            
  400.             if(showSql)
  401.                 this.sqlLogger.infoSql(sql, params);
  402.            
  403.             pstmt = _createPreparedStatement(sql);
  404.             this.jdbcParameterUtilities.setParameters(pstmt, params);
  405.            
  406.             rs =  pstmt.executeQuery();
  407.             return rs.next();
  408.            
  409.         }catch(Exception e){
  410.             throw new ServiceException(e.getMessage(),e);
  411.         }
  412.         finally{
  413.             try{
  414.                 if(rs!=null){
  415.                     rs.close();
  416.                 }
  417.             }catch(Exception eClose){}
  418.             try{
  419.                 if(pstmt!=null){
  420.                     pstmt.close();
  421.                 }
  422.             }catch(Exception eClose){
  423.                 // close
  424.             }
  425.         }
  426.     }
  427.    
  428.     public long count(String sql,boolean showSql,JDBCObject ... params ) throws ServiceException{
  429.        
  430.         PreparedStatement pstmt = null;
  431.         ResultSet rs = null;
  432.         try{
  433.            
  434.             if(showSql)
  435.                 this.sqlLogger.infoSql(sql, params);
  436.            
  437.             pstmt = _createPreparedStatement(sql);
  438.             this.jdbcParameterUtilities.setParameters(pstmt, params);
  439.            
  440.             rs =  pstmt.executeQuery();
  441.             if(rs.next())
  442.                 return rs.getLong(1);
  443.             else
  444.                 return 0;
  445.            
  446.         }catch(Exception e){
  447.             throw new ServiceException(e.getMessage(),e);
  448.         }
  449.         finally{
  450.             try{
  451.                 if(rs!=null){
  452.                     rs.close();
  453.                 }
  454.             }catch(Exception eClose){}
  455.             try{
  456.                 if(pstmt!=null){
  457.                     pstmt.close();
  458.                 }
  459.             }catch(Exception eClose){
  460.                 // close
  461.             }
  462.         }
  463.     }
  464.    
  465. }