1 Reply Latest reply on Feb 3, 2011 12:13 PM by Hernán Chanfreau

    ¿Se pueden realizar servicios CRUD sin necesidad de utilizar lenguage HQL en una aplicacion java?...¿Como lo haría?

    William Sierra Newbie

      Soy nuevo en el manejo de Hibernate, y tengo muchas dudas.

       

      En este momento estoy desarrollando una pequeña aplicacion utilizando NetBeans 6.1.9 y MySQL 5. La persistencia quiero manejarla con

      Hibernate.

       

      Ya he realizado algunos ejercicios como son: Creacion del archivo de configuracion de Hibernate (Hibernate.cfg.xml), el archivo de ingenieria inverza(hibernate.reveng.xml), tambien genere los POJOs y las clases entidad a partir de una basa de datos ralacional.

       

      Nota: Estoy manejando una arquitectura MVC. Ya he creado JFrame, donde he relizado una consulta pero creando un

      consulta HQL. Este es el codigo del jFrame.

       

       

      /**

      *

      * @author William

      */

      public class SoftDietas extends javax.swing.JFrame {

       

          /** Creates new form SoftDietas */

          public SoftDietas() {

              initComponents();

          }

       

       

      private static String QUERY= "from Lote a where a.idLote like '";

       

          private void runQueryBasedOnFirstName() {

              executeHQLQuery(QUERY + id.getText() + "%'");

          }

       

          /** 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")

          // <editor-fold defaultstate="collapsed" desc="Generated Code">                         

          private void initComponents() {

       

              buscar = new javax.swing.JButton();

              jLabel1 = new javax.swing.JLabel();

              jScrollPane1 = new javax.swing.JScrollPane();

              resultado = new javax.swing.JTable();

              id = new javax.swing.JTextField();

              jButton1 = new javax.swing.JButton();

              jTextField1 = new javax.swing.JTextField();

              jTextField2 = new javax.swing.JTextField();

              jLabel2 = new javax.swing.JLabel();

              jLabel3 = new javax.swing.JLabel();

       

              setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

       

              buscar.setText("OK");

              buscar.addActionListener(new java.awt.event.ActionListener() {

                  public void actionPerformed(java.awt.event.ActionEvent evt) {

                      buscarActionPerformed(evt);

                  }

              });

       

              jLabel1.setText("Digite el ID del lote");

       

              resultado.setModel(new javax.swing.table.DefaultTableModel(

                  new Object [][] {

                      {null, null, null, null},

                      {null, null, null, null},

                      {null, null, null, null},

                      {null, null, null, null}

                  },

                  new String [] {

                      "Title 1", "Title 2", "Title 3", "Title 4"

                  }

              ));

              jScrollPane1.setViewportView(resultado);

       

              id.setText("jTextField1");

       

              jButton1.setText("Cargar");

              jButton1.addActionListener(new java.awt.event.ActionListener() {

                  public void actionPerformed(java.awt.event.ActionEvent evt) {

                      jButton1ActionPerformed(evt);

                  }

              });

       

              jTextField1.setText("jTextField1");

       

              jTextField2.setText("jTextField2");

       

              jLabel2.setText("Digite el id del lote");

       

              jLabel3.setText("Digite el nombre del lote");

       

              javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

              getContentPane().setLayout(layout);

              layout.setHorizontalGroup(

                  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                  .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()

                      .addGap(30, 30, 30)

                      .addComponent(jLabel1)

                      .addGap(18, 18, 18)

                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                          .addComponent(buscar)

                          .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE))

                      .addGap(158, 158, 158))

                  .addGroup(layout.createSequentialGroup()

                      .addContainerGap()

                      .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)

                      .addContainerGap(15, Short.MAX_VALUE))

                  .addGroup(layout.createSequentialGroup()

                      .addGap(73, 73, 73)

                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

                          .addComponent(jLabel3)

                          .addComponent(jLabel2))

                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

                          .addComponent(jButton1)

                          .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)

                          .addComponent(jTextField1))

                      .addContainerGap(94, Short.MAX_VALUE))

              );

              layout.setVerticalGroup(

                  layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                  .addGroup(layout.createSequentialGroup()

                      .addGap(24, 24, 24)

                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                          .addComponent(jLabel1)

                          .addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                      .addComponent(buscar)

                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                      .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)

                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)

                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                          .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                          .addComponent(jLabel2))

                      .addGap(18, 18, 18)

                      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                          .addComponent(jLabel3)

                          .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))

                      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

                      .addComponent(jButton1)

                      .addGap(40, 40, 40))

              );

       

              pack();

          }// </editor-fold>                       

       

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

       

              if (!id.getText().trim().equals("")) {

                  runQueryBasedOnFirstName();

              // TODO add your handling code here:

              }

          }                                     

       

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

              // TODO add your handling code here:

          }                                       

       

          public static void main(String args[]) {

              java.awt.EventQueue.invokeLater(new Runnable() {

       

                  public void run() {

                      new SoftDietas().setVisible(true);

                  }

              });

          }

       

       

          // Variables declaration - do not modify                    

          private javax.swing.JButton buscar;

          private javax.swing.JTextField id;

          private javax.swing.JButton jButton1;

          private javax.swing.JLabel jLabel1;

          private javax.swing.JLabel jLabel2;

          private javax.swing.JLabel jLabel3;

          private javax.swing.JScrollPane jScrollPane1;

          private javax.swing.JTextField jTextField1;

          private javax.swing.JTextField jTextField2;

          private javax.swing.JTable resultado;

          // End of variables declaration                  

       

      private void executeHQLQuery(String hql) {

              try {

                  Session session = HibernateUtil.getSessionFactory().openSession();

                  session.beginTransaction();

                  org.hibernate.Query q= session.createQuery(hql);

                  List resultList = q.list();

                  displayResult(resultList);

                  session.getTransaction().commit();

              } catch (HibernateException he) {

                  JOptionPane.showInputDialog("Datos no encontrados");

                  he.printStackTrace();

              }

       

          }

      private void displayResult(List resultList) {

              Vector<String> tableHeaders = new Vector<String>();

              Vector tableData = new Vector();

              tableHeaders.add("Codigo del lote");

              tableHeaders.add("Nombre");

       

              for (Object o : resultList) {

                  Lote lote = (Lote) o;

                  Vector<Object> oneRow = new Vector<Object>();

                  oneRow.add(lote.getIdLote());

                  oneRow.add(lote.getNombre());

       

                  tableData.add(oneRow);

              }

              resultado.setModel(new DefaultTableModel(tableData, tableHeaders));

       

          }

      }

       

      Las dusdas que tengon son:

       

      1. Como puedo realizar consultas a la base de datos sin utilizar sentencias HQL.

      2. Que configuraciones adicionales hay que realizar.

      3. Teneindo en cuenta la arquitectura MVC, que debo tener en cuenta para no sairme de la misma.

       

      Agradezco sus respuestas.