Objective
We will learn how to use hibernate to connect to a database in an application of edit customer information that we have studied in the tutorial of JDBC. The architecture and the design for the module is no-changed from that tutorial, so you could refer to that tutorial to see the class diagram and the sequence diagram.
– Step 1: create a Java project in Eclipse with these packages and classes (focus only on the selected classes):

– Step 2: add hibernate library file (download from http://www.hibernate.org/downloads) into JRE system library of the project:

– Step 3: create a database named “hotel” in MySQL, in which create a table named “tblclient” with these columns:

– Step 4: Edit the file Hibernate.cfg.xml as:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3307/hotel</property><!-- need to be modified-->
<property name="hibernate.connection.characterEncoding">UTF-8</property>
<property name="hibernate.connection.autoReconnect">true</property>
<property name="hibernate.connection.useSSL">false</property>
<property name="hibernate.connection.CharSet">utf8</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.useUnicode">true</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.username">root</property>
<property name="connection.password">xxx</property><!-- need to be modified-->
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.search.backend.type">lucene</property>
<property name="hibernate.search.backend.lucene_version">LATEST</property>
<mapping class="model.Customer"/>
</session-factory>
</hibernate-configuration>
Note that some parts in the content you need to edit to adapt to your configuration.
Class Customer
package model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "tblclient")
public class Customer implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "idcard")
private String idCard;
@Column(name = "address")
private String address;
@Column(name = "tel")
private String tel;
@Column(name = "email")
private String email;
@Column(name = "note")
private String note;
public Customer() {
super();
}
public Customer(String name, String idCard, String address, String tel, String email, String note) {
super();
this.name = name;
this.idCard = idCard;
this.address = address;
this.tel = tel;
this.email = email;
this.note = note;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
Class: DAO
package control.dao;
import java.io.File;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class DAO {
public static Session session;
public DAO(){
if(session == null){
try {
session = new Configuration().configure(new File("resources/hibernate.cfg.xml"))
.buildSessionFactory().openSession();
}catch (HibernateException ex) {
ex.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
Class: CustomerDAO
package control.dao;
import java.util.ArrayList;
import model.Customer;
public class CustomerDAO extends DAO{
public CustomerDAO() {
super();
// TODO Auto-generated constructor stub
}
/**
* search all clients in the tblClient whose name contains the @key
* @param key
* @return list of client whose name contains the @key
*/
@SuppressWarnings("unchecked")
public ArrayList<Customer> searchCustomer(String key){
ArrayList<Customer> result = (ArrayList<Customer>)session.createQuery("from Customer where name like '%"+key+"%'").list();
return result;
}
/**
* update the @client
* @param client
*/
public void editCustomer(Customer client){
session.update(client);
return;
}
}
Class: SearchCustomerFrm
package view;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import control.dao.CustomerDAO;
import model.Customer;
public class SearchCustomerFrm extends JFrame implements ActionListener{
private ArrayList<Customer> listCustomer;
private JTextField txtKey;
private JButton btnSearch;
private JTable tblResult;
public SearchCustomerFrm(){
super("Search customer to edit");
listCustomer = new ArrayList<Customer>();
JPanel pnMain = new JPanel();
pnMain.setSize(this.getSize().width-5, this.getSize().height-20);
pnMain.setLayout(new BoxLayout(pnMain,BoxLayout.Y_AXIS));
pnMain.add(Box.createRigidArea(new Dimension(0,10)));
JLabel lblHome = new JLabel("Search a customer to edit");
lblHome.setAlignmentX(Component.CENTER_ALIGNMENT);
lblHome.setFont (lblHome.getFont ().deriveFont (20.0f));
pnMain.add(lblHome);
pnMain.add(Box.createRigidArea(new Dimension(0,20)));
JPanel pn1 = new JPanel();
pn1.setLayout(new BoxLayout(pn1,BoxLayout.X_AXIS));
pn1.setSize(this.getSize().width-5, 20);
pn1.add(new JLabel("Client name: "));
txtKey = new JTextField();
pn1.add(txtKey);
btnSearch = new JButton("Search");
btnSearch.addActionListener(this);
pn1.add(btnSearch);
pnMain.add(pn1);
pnMain.add(Box.createRigidArea(new Dimension(0,10)));
JPanel pn2 = new JPanel();
pn2.setLayout(new BoxLayout(pn2,BoxLayout.Y_AXIS));
tblResult = new JTable();
JScrollPane scrollPane= new JScrollPane(tblResult);
tblResult.setFillsViewportHeight(false);
scrollPane.setPreferredSize(new Dimension(scrollPane.getPreferredSize().width, 250));
tblResult.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int column = tblResult.getColumnModel().getColumnIndexAtX(e.getX()); // get the coloum of the button
int row = e.getY() / tblResult.getRowHeight(); // get the row of the button
// *Checking the row or column is valid or not
if (row < tblResult.getRowCount() && row >= 0 && column < tblResult.getColumnCount() && column >= 0) {
(new EditCustomerFrm(listCustomer.get(row))).setVisible(true);
dispose();
}
}
});
pn2.add(scrollPane);
pnMain.add(pn2);
this.add(pnMain);
this.setSize(600,300);
this.setLocation(200,10);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JButton btnClicked = (JButton)e.getSource();
if(btnClicked.equals(btnSearch)){
if((txtKey.getText() == null)||(txtKey.getText().length() == 0))
return;
listCustomer = (new CustomerDAO()).searchCustomer(txtKey.getText().trim());
String[] columnNames = {"Id", "Name", "idCard", "Address", "Email", "Tel", "Note"};
String[][] value = new String[listCustomer.size()][columnNames.length];
for(int i=0; i<listCustomer.size(); i++){
value[i][0] = listCustomer.get(i).getId() +"";
value[i][1] = listCustomer.get(i).getName();
value[i][2] = listCustomer.get(i).getIdCard();
value[i][3] = listCustomer.get(i).getAddress();
value[i][4] = listCustomer.get(i).getEmail();
value[i][5] = listCustomer.get(i).getTel();
value[i][6] = listCustomer.get(i).getNote();
}
DefaultTableModel tableModel = new DefaultTableModel(value, columnNames) {
@Override
public boolean isCellEditable(int row, int column) {
//unable to edit cells
return false;
}
};
tblResult.setModel(tableModel);
}
}
public static void main(String[] args) {
SearchCustomerFrm view = new SearchCustomerFrm();
view.setVisible(true);
}
}
Class: EditCustomerFrm
package view;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import control.dao.CustomerDAO;
import model.Customer;
public class EditCustomerFrm extends JFrame implements ActionListener{
private Customer customer;
private JTextField txtId, txtName, txtIdcard, txtAddress, txtEmail, txtTel, txtNote;
private JButton btnUpdate, btnReset;
public EditCustomerFrm(Customer client){
super("Edit a customer");
this.customer = client;
JPanel pnMain = new JPanel();
pnMain.setSize(this.getSize().width-5, this.getSize().height-20);
pnMain.setLayout(new BoxLayout(pnMain,BoxLayout.Y_AXIS));
pnMain.add(Box.createRigidArea(new Dimension(0,10)));
JLabel lblHome = new JLabel("Edit a customer information");
lblHome.setAlignmentX(Component.CENTER_ALIGNMENT);
lblHome.setFont (lblHome.getFont ().deriveFont (20.0f));
pnMain.add(lblHome);
pnMain.add(Box.createRigidArea(new Dimension(0,20)));
txtId = new JTextField(15);
txtId.setEditable(false);
txtName = new JTextField(15);
txtIdcard = new JTextField(15);
txtAddress = new JTextField(15);
txtEmail = new JTextField(15);
txtTel = new JTextField(15);
txtNote = new JTextField(15);
btnUpdate = new JButton("Update");
btnReset = new JButton("Reset");
JPanel content = new JPanel();
content.setLayout(new GridLayout(8,2));
content.add(new JLabel("Customer ID:")); content.add(txtId);
content.add(new JLabel("Name:")); content.add(txtName);
content.add(new JLabel("Idcard:")); content.add(txtIdcard);
content.add(new JLabel("Address:")); content.add(txtAddress);
content.add(new JLabel("Email:")); content.add(txtEmail);
content.add(new JLabel("Tel:")); content.add(txtTel);
content.add(new JLabel("Note:")); content.add(txtNote);
content.add(btnUpdate); content.add(btnReset);
pnMain.add(content);
btnUpdate.addActionListener(this);
btnReset.addActionListener(this);
initForm();
this.setContentPane(pnMain);
this.setSize(600,300);
this.setLocation(200,10);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
private void initForm(){
if(customer != null){
txtId.setText(customer.getId()+"");
txtName.setText(customer.getName());
txtIdcard.setText(customer.getIdCard());
txtAddress.setText(customer.getAddress());
txtEmail.setText(customer.getEmail());
txtTel.setText(customer.getTel());
txtNote.setText(customer.getNote());
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JButton btnClicked = (JButton)e.getSource();
if(btnClicked.equals(btnReset)){
initForm();
return;
}
if(btnClicked.equals(btnUpdate)){
customer.setName(txtName.getText());
customer.setIdCard(txtIdcard.getText());
customer.setAddress(txtAddress.getText());
customer.setEmail(txtEmail.getText());
customer.setTel(txtTel.getText());
customer.setNote(txtNote.getText());
(new CustomerDAO()).editCustomer(customer);
JOptionPane.showMessageDialog(this, "Update succesfully!");
this.dispose();
}
}
}