Objective
We will learn how to use hibernate to connect to a database in a concrete application of Login.
Architect of a hibernate application
A hibernate application could have five main components as follows:
- DB tables: a database in any DBMS, in this example that is hotelmanagement in MySQL
- mapping config files: these xml file will config how a tables from DB could be mapped into a POJO class
- POJO (Plain Old Java Object) classes: once being mapped from a BD, these classes will play the role as that of corresponding table.
- Hibernate config file: this xml file will config how to connect to the database, and point out where the mapping config files are stored.
- DAO/control classes: the business layer of application
- View classes: the GUI layer of application
Now let start to develop an application of login using this architect.
- Step 1: create a Java project in Eclipse with these packages and 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 "hotelmanagement" in MySQL, in which create a table named "tblUser" 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://hibernate.sourceforge.net/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:3306/hotelmanagement </property>
<property name="connection.username">root</property>
<property name="connection.password">12345678</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect </property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class"> org.hibernate.cache.NoCacheProvider
</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Note that the red marked parts are the content you need to edit base on your configuration.
- Step 5: create POJO class of User:
package model;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private Integer id;
private String username;
private String password;
private String fullName;
private String idCardNumber;
private String idCardType;
private String address;
private String description;
public User(){
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getIdCardNumber() {
return idCardNumber;
}
public void setIdCardNumber(String idCardNumber) {
this.idCardNumber = idCardNumber;
}
public String getIdCardType() {
return idCardType;
}
public void setIdCardType(String idCardType) {
this.idCardType = idCardType;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- Step 6: Config the User.hbm.xml file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="model.User" table="tbluser" >
<id name="id" type="int" column="id" >
<generator class="native"/>
</id>
<property name="username">
<column name="username" />
</property>
<property name="password">
<column name="password"/>
</property>
<property name="fullName">
<column name="fullName" />
</property>
<property name="idCardNumber">
<column name="idCardNumber"/>
</property>
<property name="idCardType">
<column name="idCardType" />
</property>
<property name="address">
<column name="address"/>
</property>
<property name="description">
<column name="description" />
</property>
</class>
</hibernate-mapping>
- Step 7: HibernateUser class
package control;
import java.util.List;
import model.User;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUser {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public boolean checkLogin(User user){
boolean result = false;
Session session = this.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<User> users = null;
String sql = "FROM User U WHERE U.username = :username AND U.password = :password";
try {
Query q = session.createQuery(sql);
q.setParameter("username", user.getUsername());
q.setParameter("password", user.getPassword());
users = (List<User>)q.list();
if (users.size() > 0) result = true;
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return result;
}
}
- Step 8: LoginControl class
package control;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import model.User;
import view.LoginView;
public class LoginControl {
private User model;
private LoginView view;
public LoginControl(LoginView view){
this.view = view;
view.addLoginListener(new LoginListener());
}
class LoginListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
model = view.getUser();
HibernateUser hu = new HibernateUser();
if(hu.checkLogin(model)){
view.showMessage("Login succesfully!");
}else{
view.showMessage("Invalid username and/or password!");
}
} catch (Exception ex) {
view.showMessage(ex.getStackTrace().toString());
}
}
}
public static void main(String[] args) {
LoginView view = new LoginView();
LoginControl controller = new LoginControl(view);
view.setVisible(true);
}
}
- Step 9: LoginView class
package view;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import model.User;
public class LoginView extends JFrame implements ActionListener{
private JTextField txtUsername;
private JPasswordField txtPassword;
private JButton btnLogin;
private User model;
public LoginView(){
super("Login MVC using Hibernate");
txtUsername = new JTextField(15);
txtPassword = new JPasswordField(15);
txtPassword.setEchoChar('*');
btnLogin = new JButton("Login");
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(new JLabel("Username:"));
content.add(txtUsername);
content.add(new JLabel("Password:"));
content.add(txtPassword);
content.add(btnLogin);
btnLogin.addActionListener(this);
this.setContentPane(content);
this.pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
}
public User getUser(){
model = new User();
model.setUsername(txtUsername.getText());
model.setPassword(txtPassword.getText());
return model;
}
public void showMessage(String msg){
JOptionPane.showMessageDialog(this, msg);
}
public void addLoginListener(ActionListener log) {
btnLogin.addActionListener(log);
}
}
Results
Login interface:
Login success interface:
Login failed interface:
- Step 2: add hibernate library file (download from http://www.hibernate.org/downloads) into JRE system library of the project:
ReplyDeleteCould you tell me how to do this, please?
p/s: Khổ quá thầy à, tiếng anh@@
- create your project
Delete- right click on: JRE System library (the lowest directory under your project name)
- choose Build Path
- choose edit the build path
- a child window will be appeared, click on the second button on the right hand: Add External JAR files
- choose the path to the directory containing the .jar files and select all necessary files, then click OK
Thanks, help me!
Deleteyou could see these instructions in this topic:
Deletehttp://coderandcode.blogspot.com/2013/08/how-to-add-external-library-file-jar-to.html
thầy ơi link hibernate library file (download from http://www.hibernate.org/downloads) bị hỏng rồi.
ReplyDeletecause of server error! you should wait until it does work again! ;)
DeleteI found this library in another website http://sourceforge.net/projects/hibernate/files/
Deletemy program are run correctly but there are some warning :
http://i1032.photobucket.com/albums/a410/tranthanhbvh/uphibrnate.jpg
can you show me what about it?
your downloaded hibernate lib's version is not suitable for your code!
Delete