martes, 16 de abril de 2013

MyBatis 3.2 usando anotaciones

Bueno voy mostrar un ejemplo donde enviaremos un parámetro desde una clase de java y nos retornada un VARCHAR desde Oracle que será consultado en un función que se encuentra dentro de un paquete.


Para esto comenzaremos creando el paquete y la función, usaremos HR para esto(se crea cuando instalamos el Oracle):
create or replace 
PACKAGE PRUEBAMYBATIS
AS
FUNCTION obtenerNombres(cEmp_Id_in IN NUMBER)
RETURN VARCHAR2;
END;
/
create or replace 
PACKAGE BODY PRUEBAMYBATIS
AS
    FUNCTION obtenerNombres(cEmp_Id_in IN NUMBER)
    RETURN VARCHAR2 IS
    varName VARCHAR2(100);
    BEGIN
        SELECT (FIRST_NAME ||' '|| LAST_NAME)
        INTO   varName
        FROM   EMPLOYEES
        WHERE  EMPLOYEE_ID = cEmp_Id_in;    
    RETURN varName;
    END;
END;


Usaremos archivos de configuracion donde guardaremos inf. de la base de datos como el usuario o la clave...


# El nombre del archivo es "variablesDataBase.properties"
# Aqui almacenaremos variables de la base de datos
# no es seguro guardar aqui pero para hacer algo novedoso :=)

vIP = localhost
vPort = 1521
vSID = orcl
VUsuario = HR
vClave = prueba

Comenzaremos creando el archivo de configuracion(xmlMyBatis.xml):
 

  
    
      
      
        
        
        
        
      
    
  
  
    
  




Creamos una clase donde estarán nuestras anotaciones donde indicaremos el paquete y la función o procedimiento... Funciona igual... solo que los procedimientos no retornan valor...

 
public interface MapperPrueba {

    @Select(value = "{call #{cNomApe_out, mode=OUT, jdbcType=VARCHAR} := "
                  + "PRUEBAMYBATIS.obtenerNombres("
                  + "#{cEmp_Id_in}"
                  + ")"
                  + "}")
    @Options(statementType = StatementType.CALLABLE)
    void obtenerNombApe(Map parametros);
}

Esta clase lee el archivo de conf. y carga sus variables...
 
public class CargarVariables {
    private final static Logger log = Logger.getLogger(CargarVariables.class.getName());
    public String obtenerIPDB(){
        String tmpIP = obtenerVarProper("vIP");
        return tmpIP;
    }    
    public String obtenerPortDB(){
        String tmpPort = obtenerVarProper("vPort");
        return tmpPort;
    }        
    public String obtenerSIDDB(){
        String tmpSID = obtenerVarProper("vSID");
        return tmpSID;
    }   
    public String obtenerURL(){
        String tmpUrl = "";
        tmpUrl = "jdbc:oracle:thin:@" + obtenerIPDB() + ":" + obtenerPortDB() + ":" + obtenerSIDDB();
        return tmpUrl;
    }
    public String obtenerUsuarioDB(){
        String tmpUsuario = obtenerVarProper("VUsuario");
        return tmpUsuario;
    }
    public String obtenerClaveDB(){
        String tmpClave = obtenerVarProper("vClave");
        return tmpClave;
    }    
    public String obtenerVarProper(String nombVar){
        String tmpVar = "";
        try {
            Properties props = new Properties();
            props.load(new FileInputStream("variablesDataBase.properties"));
            tmpVar = props.getProperty(nombVar);
        } catch (IOException ex) {
            log.warning("Error : " + ex.getMessage());
        }
        return tmpVar;
    }
}
Creamos una clase que nos retornara el SqlSession para poder llamarlo cuando queramos....
public class conector {
    private final static Logger log = Logger.getLogger(conector.class.getName());
    SqlSessionFactory sqlSession;
    static CargarVariables cargarVariables = new CargarVariables();
    public SqlSessionFactory getSqlSessionMB(){
        Reader reader = null;
        try{
            reader = Resources.getResourceAsReader("JAVA/MYBATIS/xmlMyBatis.XML");
        }catch(IOException ioEx){
            log.warning("No se cargo el archivo de conf. "+ioEx.getMessage());
        }
        Properties propBD = new Properties();
        propBD.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
        propBD.setProperty("url", cargarVariables.obtenerURL());
        propBD.setProperty("username", cargarVariables.obtenerUsuarioDB());
        propBD.setProperty("password", cargarVariables.obtenerClaveDB());
        sqlSession = new SqlSessionFactoryBuilder().build(reader,propBD);
        return sqlSession;
    }
}


Y por último crearemos un main class donde enviaremos nuestro parámetro y consultaremos datos del empleado.

    public void enter(){
        SqlSession sqlSession = new conector().getSqlSessionMB().openSession();
        MapperPrueba mbMapper = sqlSession.getMapper(MapperPrueba.class);
        
        Map parametros = new HashMap();
        parametros.put("cEmp_Id_in", "100");
        mbMapper.obtenerNombApe(parametros);
        
        String tmpNomApe = parametros.get("cNomApe_out").toString();
        System.out.println("LOS DATOS SON : "+tmpNomApe)   ;
    }
Bueno esto sería mi aporte a la comunidad JAVA... por favor comenta si tienes alguna mejora o recomendación... Claro también si tienes alguna duda...
Estoy adjuntando el proyecto... dentro están las librerías y la guía de MyBatis...
http://www.mediafire.com/?vqbhwhe1firc5t3

1 comentario:

  1. Where to buy a table game with the best odds - Dr.MD
    You can bet on NFL, NBA, MLB, NHL, MLB, 경주 출장샵 NBA, WNBA, NBA, NHL, EPL, MLB, WNBA, NCAAB, 광명 출장샵 NBA, 김제 출장안마 GOLF, NHL. and other sports 포항 출장마사지 such as horse racing, 인천광역 출장안마 basketball, ice hockey,

    ResponderEliminar