【问题标题】:Filling combobox from database by using hibernate in Java在Java中使用hibernate从数据库中填充组合框
【发布时间】:2011-02-01 15:18:12
【问题描述】:

嘿嘿;

我正在用 java 中的 hibernate 开发一个基于 swing 的小型应用程序。我想从数据库列中填充组合框。我该怎么做?

我不知道在哪里(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(); 
      }    
}

【问题讨论】:

标签: java hibernate swing database jcombobox


【解决方案1】:

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

您可以在文章How to Use Combo Boxes 中了解有关JComboBox 的更多信息。

【讨论】:

    猜你喜欢
    • 2012-09-11
    • 2015-07-16
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多