简体   繁体   中英

How to populate JComboBox using hibernate?

I am creating a Swing application. I want to populate a JComboBox with data from database using Hibernate. Following is my code:

Session sess=sf.openSession();
Transaction tx=sess.beginTransaction();

List<Employee> company= (List<Employee>)sess.createQuery("from Company").list();
for(Company e:company) 
{
    String[] item= {Integer.toString(e.getID()),e.getName()};
}

It can be done like this:

import javax.swing.*;
import java.awt.FlowLayout;
import java.util.*;

public class JComboBoxExample {

  public static void main(String[] args) {

    List<Employee> employeesFromDatabase = Arrays.asList(
        new Employee(101, "John"),
        new Employee(102, "Kevin"),
        new Employee(103, "Sally"),
        new Employee(104, "Sara"));

    JComboBox<String> comboBox = new JComboBox<>();

    for (Employee employee : employeesFromDatabase) {

      StringJoiner stringJoiner = new StringJoiner(", ");
      stringJoiner.add(Integer.toString(employee.getId()));
      stringJoiner.add(employee.getName());

      comboBox.addItem(stringJoiner.toString());
    }

    JFrame f = new JFrame("Questions");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().setLayout(new FlowLayout());
    f.getContentPane().add(new JLabel("Employee"));
    f.getContentPane().add(comboBox);
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}

class Employee {

  private int id;
  private String name;

  public Employee(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM