2010-03-27 54 views
1

Heyy;通過在Java中使用休眠來從數據庫填充組合框

我正在用java開發一個基於hibernate的小型基於swing的應用程序。我想從數據庫coloumn填充組合框。我該怎麼做?

而且我不知道在哪裏(在initComponentsbuttonActionPerformd下)我需要做的。

對於使用我'的JButton,它的代碼保存在這裏:

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

int idd=Integer.parseInt(jTextField1.getText()); 

String name=jTextField2.getText(); 

String description=jTextField3.getText(); 

Session session = null; 

SessionFactory sessionFactory = new Configuration().configure() 
    .buildSessionFactory(); 

session = sessionFactory.openSession(); 

Transaction transaction = session.getTransaction(); 

    try { 


     ContactGroup con = new ContactGroup(); 

     con.setId(idd); 

     con.setGroupName(name); 
     con.setGroupDescription(description); 



     transaction.begin(); 
     session.save(con); 
     transaction.commit(); 


     } catch (Exception e) { 
     e.printStackTrace(); 
     } 

     finally{ 
     session.close(); 
     }  
} 
+0

您不應該在Swing事件派發線程中執行數據庫訪問 - 它將阻止UI直到數據庫通信完成。查看SwingWorker和本教程:http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html – 2010-03-28 11:10:12

回答

5

我不使用休眠,但鑑於命名Customer JPA實體,並命名爲CustomerJpaController一個JPA控制器,你可以這樣做這個。

更新:更新代碼以反映切換到EclipseLink(JPA 2.1)作爲持久性庫。

import java.awt.EventQueue; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.List; 
import javax.swing.JComboBox; 
import javax.swing.JFrame; 

/** 
* @see http://stackoverflow.com/a/2531942/230513 
*/ 
public class CustomerTest implements Runnable { 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new CustomerTest()); 
    } 

    @Override 
    public void run() { 
     CustomerJpaController con = new CustomerJpaController(
      Persistence.createEntityManagerFactory("CustomerPU")); 
     List<Customer> list = con.findCustomerEntities(); 
     JComboBox combo = new JComboBox(list.toArray()); 
     combo.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       JComboBox cb = (JComboBox) e.getSource(); 
       Customer c = (Customer) cb.getSelectedItem(); 
       System.out.println(c.getId() + " " + c.getName()); 
      } 
     }); 
     JFrame f = new JFrame(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.add(combo); 
     f.pack(); 
     f.setVisible(true); 
    } 
} 

對象添加到JComboBox從對象的toString()方法得到他們的顯示名稱,所以Customer進行了修改,返回getName()用於顯示目的:

@Override 
public String toString() { 
    return getName(); 
} 

您可以瞭解更多關於JComboBox文章How to Use Combo Boxes中。

+0

更多[here](http://stackoverflow.com/a/3424872/ 230513)。 – trashgod 2012-08-14 01:22:03