Filling combobox from database by using hibernate in Java
Heyy;
I am developing a small swing based application with hibernate in java. And I want fill combobox from database coloumn. How I can do that?
And I don't know in where(under initComponents
, buttonActionPerformd
) I need to do.
For saving I'am using jbutton and it's code is here :
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(开发者_StackOverflow中文版);
}
finally{
session.close();
}
}
I don't use Hibernate, but given a JPA entity named Customer
and a JPA controller named CustomerJpaController
, you can do something like this.
Update: Code updated to reflect a switch to EclipseLink (JPA 2.1) as the persistence library.
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);
}
}
Objects added to a JComboBox
get their display name from the object's toString()
method, so Customer
was modified to return getName()
for display purposes:
@Override
public String toString() {
return getName();
}
You can learn more about JComboBox
in the article How to Use Combo Boxes.
精彩评论