使用Java中的hibernate从数据库填充组合框

时间:2010-03-27 22:36:28

标签: java hibernate swing database jcombobox

Heyy;

我正在使用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(); 
      }    
}

1 个答案:

答案 0 :(得分:5)

我不使用Hibernate,但是给定一个名为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