Store procedure com hibernate,metódos abstrados classe conexão

Classe conexão

[code]package Persistencia;

import Tela.JF_Servico;
import java.io.PrintWriter;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import org.hibernate.;
import org.hibernate.cfg.
;
import java.sql.DatabaseMetaData;
import javax.sql.DataSource;

/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

/**
*

  • @author Rodrigo
    */
    public final class Conexao implements Connection{
    SessionFactory factory;
    Session session;
    Transaction t;
    CallableStatement procedure;
    Conexao con;

    public Conexao(){
    conectar();
    }

    public void desconectar(){
    t.commit();
    session.flush();
    session.close();
    }

    public void conectar(){
    factory = new Configuration().configure(“VO/hibernate.cfg.xml”).buildSessionFactory();
    session = factory.openSession();
    t = session.beginTransaction();
    }

    public Statement createStatement() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public PreparedStatement prepareStatement(String sql) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public String nativeSQL(String sql) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void setAutoCommit(boolean autoCommit) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public boolean getAutoCommit() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void commit() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void rollback() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void close() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public boolean isClosed() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public DatabaseMetaData getMetaData() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void setReadOnly(boolean readOnly) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public boolean isReadOnly() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void setCatalog(String catalog) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public String getCatalog() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void setTransactionIsolation(int level) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public int getTransactionIsolation() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public SQLWarning getWarnings() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void clearWarnings() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Map<String, Class<?>> getTypeMap() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void setHoldability(int holdability) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public int getHoldability() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Savepoint setSavepoint() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Savepoint setSavepoint(String name) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void rollback(Savepoint savepoint) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void releaseSavepoint(Savepoint savepoint) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
    throw new UnsupportedOperationException(“Erro ao chamar store procedure”);
    }

    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Clob createClob() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Blob createBlob() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public NClob createNClob() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public SQLXML createSQLXML() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public boolean isValid(int timeout) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void setClientInfo(String name, String value) throws SQLClientInfoException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public void setClientInfo(Properties properties) throws SQLClientInfoException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public String getClientInfo(String name) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Properties getClientInfo() throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public T unwrap(Class iface) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public boolean isWrapperFor(Class<?> iface) throws SQLException {
    throw new UnsupportedOperationException(“Not supported yet.”);
    }

    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
    throw new UnsupportedOperationException(“Erro ao chamar store procedure”);
    }

    public CallableStatement prepareCall(String sql) throws SQLException {

     return prepareCall(sql);
    

    }

}
[/code]

Classe serviço VO

[code]package VO;
// Generated 10/04/2011 21:06:35 by Hibernate Tools 3.2.1.GA

/**

  • Servico generated by hbm2java
    */
    public class Servico implements java.io.Serializable {

    private Double valor;
    private String nome;
    private String descricao;
    private String duracao;

    public Servico() {
    }

    public Servico(Double valor, String nome, String descricao, String duracao) {
    this.valor = valor;
    this.nome = nome;
    this.descricao = descricao;
    this.duracao = duracao;
    }

    public Double getValor() {
    return this.valor;
    }

    public void setValor(Double valor) {
    this.valor = valor;
    }
    public String getNome() {
    return this.nome;
    }

    public void setNome(String nome) {
    this.nome = nome;
    }
    public String getDescricao() {
    return this.descricao;
    }

    public void setDescricao(String descricao) {
    this.descricao = descricao;
    }
    public String getDuracao() {
    return this.duracao;
    }

    public void setDuracao(String duracao) {
    this.duracao = duracao;
    }

}

[/code]

Mapeamento da tabela serviço

[code]<?xml version="1.0"?>

 <sql-query name="sp_insere_servico" callable="true">
    <return>
        <return-property name="valor" column="valor"/>
        <return-property name="nome" column="nome"/>
        <return-property name="descricao" column="descricao"/>
        <return-property name="duracao" column="duracao"/>
</return>
{ call sp_insere_servico(?, ?, ?, ?) }
</sql-query>

</class>

[/code]

frame jf_servico

[code]/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

/*

  • JF_Servico.java
  • Created on 03/04/2011, 16:52:31
    */

package Tela;

import java.math.BigDecimal.;
import RNegocios.RN_Servico;
import VO.
;
import javax.swing.JOptionPane;

/**
*

  • @author Thyago H. Pacher
    */
    public class JF_Servico extends javax.swing.JFrame {

    /** Creates new form JF_Servico */
    public JF_Servico() {
    initComponents();
    }

    /** This method is called from within the constructor to

    • initialize the form.

    • WARNING: Do NOT modify this code. The content of this method is

    • always regenerated by the Form Editor.
      */
      @SuppressWarnings(“unchecked”)
      //
      private void initComponents() {

      label_nome = new javax.swing.JLabel();
      label_descricao = new javax.swing.JLabel();
      label_duracao = new javax.swing.JLabel();
      label_valor = new javax.swing.JLabel();
      text_nome = new javax.swing.JTextField();
      text_descricao = new javax.swing.JTextField();
      text_valor = new javax.swing.JTextField();
      text_duracao = new javax.swing.JTextField();
      botao_confirmar = new javax.swing.JButton();
      botao_sair = new javax.swing.JButton();

      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
      setTitle(“Serviço”);

      label_nome.setText(“Nome”);

      label_descricao.setText(“Descrição”);

      label_duracao.setText(“Duração”);

      label_valor.setText(“Valor”);

      text_nome.setToolTipText(“digite o nome do serviço”);

      text_descricao.setToolTipText(“o que é o serviço”);

      text_valor.setToolTipText(“qual o valor do seviço”);

      text_duracao.setToolTipText(“qual o tempo médio do serviço”);

      botao_confirmar.setText(“Confirmar”);
      botao_confirmar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      botao_confirmarActionPerformed(evt);
      }
      });

      botao_sair.setText(“Sair”);
      botao_sair.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
      botao_sairActionPerformed(evt);
      }
      });

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
      .addContainerGap()
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(label_descricao)
      .addComponent(label_nome)
      .addComponent(label_duracao)
      .addComponent(label_valor))
      .addGap(18, 18, 18)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(text_descricao, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
      .addComponent(text_nome, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
      .addComponent(text_valor, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)
      .addComponent(text_duracao, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE))
      .addGap(79, 79, 79))
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
      .addGap(209, 209, 209)
      .addComponent(botao_confirmar)
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 8, Short.MAX_VALUE)
      .addComponent(botao_sair)
      .addContainerGap())))
      );
      layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
      .addGap(37, 37, 37)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      .addComponent(label_nome)
      .addComponent(text_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
      .addGap(18, 18, 18)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      .addComponent(label_descricao)
      .addComponent(text_descricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
      .addGap(18, 18, 18)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      .addComponent(label_duracao)
      .addComponent(text_duracao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
      .addGap(18, 18, 18)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(label_valor)
      .addComponent(text_valor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
      .addComponent(botao_confirmar)
      .addComponent(botao_sair))
      .addContainerGap())
      );

      pack();
      }//

    private void botao_sairActionPerformed(java.awt.event.ActionEvent evt) {
    this.dispose();
    }

    private void botao_confirmarActionPerformed(java.awt.event.ActionEvent evt) {

     Servico cadServ = new Servico();
    
     cadServ.setValor    (Double.valueOf(text_valor.getText()));
     cadServ.setNome     (text_nome.getText());     
     cadServ.setDescricao(text_descricao.getText());
     cadServ.setDuracao  (text_duracao.getText());
    
     RN_Servico cadRNServ = new RN_Servico();
     String mensagem      = cadRNServ.gravarObjeto(cadServ);
     
     JOptionPane.showMessageDialog(null, mensagem);
    

    }

    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new JF_Servico().setVisible(true);
    }
    });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton botao_confirmar;
    private javax.swing.JButton botao_sair;
    private javax.swing.JLabel label_descricao;
    private javax.swing.JLabel label_duracao;
    private javax.swing.JLabel label_nome;
    private javax.swing.JLabel label_valor;
    private javax.swing.JTextField text_descricao;
    private javax.swing.JTextField text_duracao;
    private javax.swing.JTextField text_nome;
    private javax.swing.JTextField text_valor;
    // End of variables declaration

}[/code]

ServicoRN

[code]/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

package RNegocios;

/**
*

  • @author Thyago H. Pacher
    /
    import Persistencia.
    ;
    import VO.;
    import java.util.
    ;

public class RN_Servico {

public String gravarObjeto(Servico cadServ){
    Pers_Servico cadPersServico = new Pers_Servico();
    String  mensagem            = cadPersServico.gravarObjeto(cadServ);
    return  mensagem;
}

public String alterarObjeto(Servico cadServ){
    Pers_Servico cadPersServico = new Pers_Servico();
    String      mensagem        = cadPersServico.alterarObjeto(cadServ);
    return      mensagem;
}

public String excluirObjeto(Servico cadServ){
    Pers_Servico cadPersServico = new Pers_Servico();
    String      mensagem        = cadPersServico.excluirObjeto(cadServ);
    return  mensagem;
}

//ver que campo vai ser usado para procurado
public Servico retornarNomeTel(String CPF){

    Pers_Servico cadPersServico = new Pers_Servico();
    Servico cadServ           = cadPersServico.retornarNomeTel(CPF);
    return cadServ;
}

//volta a consulta de todos os elementos
public Vector consultaTodos(){
Vector vetorGeral = new Vector();

    Pers_Servico cadPersServico = new Pers_Servico();
//    vetorGeral           = cadPers.consultaTodos();
    return vetorGeral;
}

}
[/code]

servico persistencia

[code]/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

package Persistencia;

import Tela.JF_Servico;
import VO.*;

//imports usados para hibernate(funcionando em pc utfpr)
import java.sql.;
import java.util.
;
import org.hibernate.;
import org.hibernate.cfg.
;

/**
*

  • @author Thyago H. Pacher
    */
    public class Pers_Servico {

    Conexao con;
    CallableStatement procedure;
    Servico cadServ = new Servico();

    public String gravarObjeto(Servico cadServ){

     String mensagem;
    

//utilizando uma store procedure
try {
con.conectar();
SessionFactory factory = new Configuration().
configure(“VO/hibernate.cfg.xml”).
buildSessionFactory();

        Connection connection = procedure.getConnection();
        Session session = factory.openSession();
        Transaction t   = session.beginTransaction();
        procedure = connection.prepareCall("{call SP_INSERE_SERVICO(?, ?, ?, ?)}");

        procedure.setDouble(1, cadServ.getValor());
        procedure.setString(2, cadServ.getNome());
        procedure.setString(3, cadServ.getDescricao());
        procedure.setString(4,cadServ.getDuracao());
        
        procedure.execute();
        t.commit();
        session.flush();
        session.close();
        con.desconectar();
        mensagem = "Gravou Sucesso";

    } catch (Exception e) {
        mensagem = "Erro na gravação:\n" + e;
    }

    return mensagem;

}

public String alterarObjeto(Servico cadServ){

String msg;

try{

    SessionFactory factory = new Configuration().
            configure("VO/hibernate.cfg.xml").
            buildSessionFactory();

    Session session = factory.openSession();
    Transaction t   = session.beginTransaction();
    session.update(cadServ);
    t.commit();
    session.flush();
    session.close();

    msg = "Atualizou com sucesso!";

    }catch(Exception e){
        msg = "Erro:\n" + e.getMessage();
    }

 return msg;

}

public String excluirObjeto(Servico cadServ){

String msg;

try{

    SessionFactory factory = new Configuration().
            configure("VO/hibernate.cfg.xml").
            buildSessionFactory();

    Session session = factory.openSession();
    Transaction t   = session.beginTransaction();
    session.delete(cadServ);
    t.commit();
    session.flush();
    session.close();

    msg = "Gravou com sucesso!";

    }catch(Exception e){
        msg = "Erro:" + e.getMessage();
    }

 return msg;

}

public Servico retornarNomeTel(String CPF){

    SessionFactory factory = new Configuration().
            configure("VO/hibernate.cfg.xml").
            buildSessionFactory();
    Session session = factory.openSession();
    cadServ = (Servico) session.get(Servico.class, new Integer(CPF));

    return cadServ;
}

}[/code]

tabela servico no banco de dados

CREATE TABLE "SERVICO" ( "CODSERVICO" INTEGER NOT NULL, "VALOR" DOUBLE PRECISION, "NOME" VARCHAR(50), "DESCRICAO" VARCHAR(100), "DURACAO" VARCHAR(20), PRIMARY KEY ("CODSERVICO") );

Configuração do hibernate

[code]<?xml version="1.0" encoding="UTF-8"?>

org.hibernate.dialect.FirebirdDialect org.firebirdsql.jdbc.FBDriver jdbc:firebirdsql:localhost:H:\Estacionamento\Sistema_Estacionamento.fdb sysdba masterkey true true [/code]

Arquivo de engenharia reversa

[code]<?xml version="1.0" encoding="UTF-8"?>

[/code] Da a seguinte mensagem quando tento fazer o cadastro java.lang.nullpointerexception

qualquer arquivo q alguem veja que está faltando… ou sintaxe da um tok

ainda ninguem respondeu…

Agora estou em dúvida a um mapeamento correto de store procedure…,como podem ver já comecei acima olha só abaixo o meu mapeamento com utilização de store procedures,se alguem puder dar uma corrigida

[code]<?xml version="1.0"?>

 <sql-query name="SP_INSERE_SERVICO" callable="true">
    <return alias="servico" class="VO.Servico">
        <return-property name="valor"     column="valor"/>
        <return-property name="nome"      column="nome"/>
        <return-property name="descricao" column="descricao"/>
        <return-property name="duracao"   column="duracao"/>
</return>
{ call SP_INSERE_SERVICO(?, ?, ?, ?) }
</sql-query>

</class>

[/code]