Nah dengan Hibernate masalah koneksi database di handle menjadi satu file yang biasanya dinamai hibernate.cfg.xml, itulah sedikit kemudahan dari hibernate untuk lebih jelasnya silahkan kunjungi web resmina langsung www.hibernate.org/
Oke kembali ke bahasan semula yaitu membuat aplikasi sederhana dengan Java dan hibernate. Langkah-langkahnya sebagai berikut:
Buat tabel dengan field berikut:
1. Buka Netbeans Anda, disini saya menggunakan Netbeans 6.9.1 yang udah terintegrasi dengan Hibernate. Buat new Project
Beri nama person, dan klik Finish.
2. Selanjutnya tambahkan Library Hibernate, Persistance dan Mysql Connector, untuk Mysql Connector sesuaikan dengan database yang Anda gunakan, untuk lengkapnya seperti gambar dibawah ini:
3. Selanjutnya mulai codeing..hehe buat file hibernate.cfg.xml
klik Next, beri nama file dengan hibernate.cfg selanjutnya anda harus mensetting database Connection dan database Dialect sesuaikan dengan database yang anda gunakan, caranya sangan mudah sekali jadi tidak perlu dijelasin :)
Selanjutnya masukkan code berikut pada life yang anda buat tadi:
<?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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/person</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="Person.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Sedikit penjelasan:
hibernate.dialect: digunakan untuk memilih database yang saya pake.
hibernate.connection.driver_class: digunakan untuk driver yang saya gunakan.
hibernate.connection.url: digunakan untuk menentukan lokasi database
hibernate.connection.username: digunakan untuk username koneksi ke database
hibernate.connection.password: digunakan untuk password koneksi database
settingan diatas digunakan untuk database mysql untuk yang lain anda bisa mengubahnya sendiri
4. Selanjutnya kita buat model, maksudnya file yang terintegrasi dengan databasi, beri nama Person.java
/*
* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.model;
/**
*
* @author Syauqil
*/
public class Person {
private int id;
private String nama;
private String telepon;
private String alamat;
public Person() {
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getTelepon() {
return telepon;
}
public void setTelepon(String telepon) {
this.telepon = telepon;
}
}
5. Selanjutnya buat file Person.hbm.xml, file ini digunakan untuk mapping tabel database:* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.model;
/**
*
* @author Syauqil
*/
public class Person {
private int id;
private String nama;
private String telepon;
private String alamat;
public Person() {
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getTelepon() {
return telepon;
}
public void setTelepon(String telepon) {
this.telepon = telepon;
}
}
pada gambar diatas klik next, pada Class to Map ketikkan file yang kita buat pada langkah sebelumnya. Pada Configuration File pilih file hibernate.cfg.xml dan pada Database table pilih database yang anda gunakan. lalu klik finish.
6. Selanjutnya buat file DAO (Data Access Object) disini saya beri nama PersonDAO.java:
/*
* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.DAO;
import java.util.List;
import org.hibernate.HibernateException;
import com.syauqil.person.model.Person;
/**
*
* @author Syauqil
*/
public interface PersonDAO {
public void insert(Person person) throws HibernateException;
public void update(Person person) throws HibernateException;
public void delete(Person person) throws HibernateException;
List <Person> SelectAll() throws HibernateException;
List<Person> GetByName(String nama) throws HibernateException;
}
7. Selanjutnya buat file HibernateUtil.java, file ini digunakan untuk meload file hibernate.cfg.xml yang telah kita buat pada bagian awal:* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.DAO;
import java.util.List;
import org.hibernate.HibernateException;
import com.syauqil.person.model.Person;
/**
*
* @author Syauqil
*/
public interface PersonDAO {
public void insert(Person person) throws HibernateException;
public void update(Person person) throws HibernateException;
public void delete(Person person) throws HibernateException;
List <Person> SelectAll() throws HibernateException;
List<Person> GetByName(String nama) throws HibernateException;
}
/*
* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.syauqil.person.DAO.Implement.PersonDAOImpl;
import com.syauqil.person.DAO.PersonDAO;
/**
*
* @author Syauqil
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static final PersonDAO personDao;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
personDao = new PersonDAOImpl(sessionFactory);
} catch (Throwable e) {
System.err.println("Inisialisasi sessionFactory gagal "+e);
throw new ExceptionInInitializerError(e);
}
}
public static PersonDAO getPersonDao() {
return personDao;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
8. Selanjutnya buat file implementasi dari file DAO diatas disini saya beri nama PersonDAOImpl.java :* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.syauqil.person.DAO.Implement.PersonDAOImpl;
import com.syauqil.person.DAO.PersonDAO;
/**
*
* @author Syauqil
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
private static final PersonDAO personDao;
static {
try {
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
personDao = new PersonDAOImpl(sessionFactory);
} catch (Throwable e) {
System.err.println("Inisialisasi sessionFactory gagal "+e);
throw new ExceptionInInitializerError(e);
}
}
public static PersonDAO getPersonDao() {
return personDao;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
/*
* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.DAO.Implement;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import com.syauqil.person.DAO.PersonDAO;
import com.syauqil.person.model.Person;
/**
*
* @author Syauqil
*/
public class PersonDAOImpl implements PersonDAO{
Session session;
SessionFactory factory;
Criteria criteria;
public PersonDAOImpl(SessionFactory factory) {
this.factory = factory;
}
public void insert(Person person) throws HibernateException {
session = factory.openSession();
try {
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
System.out.println("Sukses kang!!!");
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally{
session.close();
factory.close();
}
}
public void update(Person person) throws HibernateException {
session = factory.openSession();
try {
session.beginTransaction();
session.update(person);
session.getTransaction().commit();
System.out.println("Sukses kang!!");
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
}
public void delete(Person person) throws HibernateException {
session = factory.openSession();
try {
session.beginTransaction();
session.delete(person);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
}
public List<Person> SelectAll() throws HibernateException {
session = factory.openSession();
try {
criteria = session.createCriteria(Person.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return criteria.list();
}
public List<Person> GetByName(String nama) throws HibernateException {
session = factory.openSession();
try {
criteria = session.createCriteria(Person.class).add(Restrictions.like("nama", nama, MatchMode.ANYWHERE));
System.out.println("Sukses kang!!");
} catch (HibernateException e) {
e.printStackTrace();
}
return criteria.list();
}
}
* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.DAO.Implement;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import com.syauqil.person.DAO.PersonDAO;
import com.syauqil.person.model.Person;
/**
*
* @author Syauqil
*/
public class PersonDAOImpl implements PersonDAO{
Session session;
SessionFactory factory;
Criteria criteria;
public PersonDAOImpl(SessionFactory factory) {
this.factory = factory;
}
public void insert(Person person) throws HibernateException {
session = factory.openSession();
try {
session.beginTransaction();
session.save(person);
session.getTransaction().commit();
System.out.println("Sukses kang!!!");
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally{
session.close();
factory.close();
}
}
public void update(Person person) throws HibernateException {
session = factory.openSession();
try {
session.beginTransaction();
session.update(person);
session.getTransaction().commit();
System.out.println("Sukses kang!!");
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
}
public void delete(Person person) throws HibernateException {
session = factory.openSession();
try {
session.beginTransaction();
session.delete(person);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
factory.close();
}
}
public List<Person> SelectAll() throws HibernateException {
session = factory.openSession();
try {
criteria = session.createCriteria(Person.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return criteria.list();
}
public List<Person> GetByName(String nama) throws HibernateException {
session = factory.openSession();
try {
criteria = session.createCriteria(Person.class).add(Restrictions.like("nama", nama, MatchMode.ANYWHERE));
System.out.println("Sukses kang!!");
} catch (HibernateException e) {
e.printStackTrace();
}
return criteria.list();
}
}
9.Selanjutnya buat file controller, disini saya beri nama PersonController.java
/*
* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.controller;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.xml.bind.ParseConversionEvent;
import com.syauqil.person.DAO.PersonDAO;
import com.syauqil.person.model.Person;
import com.syauqil.person.util.HibernateUtil;
/**
*
* @author Syauqil
*/
public class PersonController {
Person person = new Person();
PersonDAO personDAO = HibernateUtil.getPersonDao();
String header[] = {"Id", "Nama", "Telepon", "Alamat"};
public void insert(String nama, String telepon, String alamat){
person.setNama(nama);
person.setTelepon(telepon);
person.setAlamat(alamat);
personDAO.insert(person);
}
public void update(String id, String nama, String telepon, String alamat){
person.setId(Integer.parseInt(id));
person.setNama(nama);
person.setTelepon(telepon);
person.setAlamat(alamat);
personDAO.update(person);
}
public void delete(String id, String nama, String telepon, String alamat){
person.setId(Integer.parseInt(id));
person.setNama(nama);
person.setTelepon(telepon);
person.setAlamat(alamat);
personDAO.delete(person);
}
public void SelectAll(JTable table){
List<Person> list = personDAO.SelectAll();
Object data[][] = new Object[list.size()][4];
int i = 0;
for(Person manusia : list){
data[i][0] = manusia.getId();
data[i][1] = manusia.getNama();
data[i][2] = manusia.getTelepon();
data[i][3] = manusia.getAlamat();
++i;
}
table.setModel(new DefaultTableModel(data, header));
}
public void GetByName(String nama, JTable table){
List<Person> list = personDAO.GetByName(nama);
Object data[][] = new Object[list.size()][4];
int i = 0;
for(Person manusia : list){
data[i][0] = manusia.getId();
data[i][1] = manusia.getNama();
data[i][2] = manusia.getTelepon();
data[i][3] = manusia.getAlamat();
++i;
}
table.setModel(new DefaultTableModel(data, header));
}
}
* Created by Muhammad Syauqil ilmi
* Copyright (c) 2012 http://aksesgratis.blogspot.com
* Rock With Java
*/
package com.syauqil.person.controller;
import java.util.List;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.xml.bind.ParseConversionEvent;
import com.syauqil.person.DAO.PersonDAO;
import com.syauqil.person.model.Person;
import com.syauqil.person.util.HibernateUtil;
/**
*
* @author Syauqil
*/
public class PersonController {
Person person = new Person();
PersonDAO personDAO = HibernateUtil.getPersonDao();
String header[] = {"Id", "Nama", "Telepon", "Alamat"};
public void insert(String nama, String telepon, String alamat){
person.setNama(nama);
person.setTelepon(telepon);
person.setAlamat(alamat);
personDAO.insert(person);
}
public void update(String id, String nama, String telepon, String alamat){
person.setId(Integer.parseInt(id));
person.setNama(nama);
person.setTelepon(telepon);
person.setAlamat(alamat);
personDAO.update(person);
}
public void delete(String id, String nama, String telepon, String alamat){
person.setId(Integer.parseInt(id));
person.setNama(nama);
person.setTelepon(telepon);
person.setAlamat(alamat);
personDAO.delete(person);
}
public void SelectAll(JTable table){
List<Person> list = personDAO.SelectAll();
Object data[][] = new Object[list.size()][4];
int i = 0;
for(Person manusia : list){
data[i][0] = manusia.getId();
data[i][1] = manusia.getNama();
data[i][2] = manusia.getTelepon();
data[i][3] = manusia.getAlamat();
++i;
}
table.setModel(new DefaultTableModel(data, header));
}
public void GetByName(String nama, JTable table){
List<Person> list = personDAO.GetByName(nama);
Object data[][] = new Object[list.size()][4];
int i = 0;
for(Person manusia : list){
data[i][0] = manusia.getId();
data[i][1] = manusia.getNama();
data[i][2] = manusia.getTelepon();
data[i][3] = manusia.getAlamat();
++i;
}
table.setModel(new DefaultTableModel(data, header));
}
}
10. Sekarang tinggal buat View, untuk tampilan saya buat seperti ini
Untuk aksi tombolnya sebagai berikut:
Insert:
String nama = textNama.getText();
String telepon = textTelepon.getText();
String alamat = textAlamat.getText();
new PersonController().insert(nama, telepon, alamat);
reset();
String telepon = textTelepon.getText();
String alamat = textAlamat.getText();
new PersonController().insert(nama, telepon, alamat);
reset();
Update:
String id = textId.getText();
String nama = textNama.getText();
String telepon = textTelepon.getText();
String alamat = textAlamat.getText();
new PersonController().update(id, nama, telepon, alamat);
reset();
String nama = textNama.getText();
String telepon = textTelepon.getText();
String alamat = textAlamat.getText();
new PersonController().update(id, nama, telepon, alamat);
reset();
Delete:
String id = textId.getText();
String nama = textNama.getText();
String telepon = textTelepon.getText();
String alamat = textAlamat.getText();
new PersonController().delete(id, nama, telepon, alamat);
reset();
String nama = textNama.getText();
String telepon = textTelepon.getText();
String alamat = textAlamat.getText();
new PersonController().delete(id, nama, telepon, alamat);
reset();
Reset:
private void reset() {
dataTable();
textId.setText("");
textNama.setText("");
textTelepon.setText("");
textAlamat.setText("");
textCari.setText("");
}
dataTable();
textId.setText("");
textNama.setText("");
textTelepon.setText("");
textAlamat.setText("");
textCari.setText("");
}
Tabel MouseClicked:
int j = tablePerson.getSelectedRow();
String id = tablePerson.getValueAt(j, 0).toString();
String nama = tablePerson.getValueAt(j, 1).toString();
String telepon = tablePerson.getValueAt(j, 2).toString();
String alamat = tablePerson.getValueAt(j, 3).toString();
textId.setText(id);
textNama.setText(nama);
textTelepon.setText(telepon);
textAlamat.setText(alamat);
String id = tablePerson.getValueAt(j, 0).toString();
String nama = tablePerson.getValueAt(j, 1).toString();
String telepon = tablePerson.getValueAt(j, 2).toString();
String alamat = tablePerson.getValueAt(j, 3).toString();
textId.setText(id);
textNama.setText(nama);
textTelepon.setText(telepon);
textAlamat.setText(alamat);
Cari:
String cari = textCari.getText();
new PersonController().GetByName(cari, tablePerson);
new PersonController().GetByName(cari, tablePerson);
Code untuk meload data dari database:
public void dataTable(){
new PersonController().SelectAll(tablePerson);
}
void diatas letakkan pada constructor.new PersonController().SelectAll(tablePerson);
}
Berikut cuplikan file-file yang kita buat tadi:
Akhirnya selesai juga aplikasi sederhana kita, semoga bermanfaat :)
gan insert, update, delete nya saat di jalanin err semua,,,, bisa minta projectnya gak?
ReplyDeleteSaya coba bisa gan.. :)
ReplyDeleteNi link downloadnya... http://www.mediafire.com/?n21meq66hkgd7dh
Semoga bermanfaat...
keren gan, baiknya kodenya di rapiin gan biar lbh gampang bacanya :) thx alot
ReplyDeletenice post gan.
ReplyDeletetapi saya masi belom terlalu mengerti tentang hiberbnate gan.
ada penjelasan yang lebih cocok ga gan?? thnx :D
ane lagi bikin nih project bikin hibernate,, kok saat kita bikin 5 ID misalkan 1, 2, 3, 4, 5. nah ane delete nomer 3,, kenapa gak bisa otomatis ID 4 jadi 3, atau gak kenapa pas kita bikin ID baru kenapa langsung ke nomer 6, kenapa gak mengisi ke kosongan nomer 3,, ane cuman nanya itu aja,, mohon bantuannya yak gan
ReplyDeleteId nya auto increment mas rhio, jadi otomatis nambah dari yang terbesar,
DeleteThis comment has been removed by the author.
ReplyDeleteNice Shared Gan. Thumps Up
ReplyDeleteThis comment has been removed by the author.
ReplyDeletegan gw kok error library pas import open project yg dishare di mediafire
ReplyDeleteni error nya
http://i1221.photobucket.com/albums/dd475/bhezooke2/Capture.png
knp ya gan??
outputnya kayak apa itu gan???
ReplyDeleteGan., kalo query untuk melakukan pencarian data ke textfield gimana ?
ReplyDeleteGan., kalo query untuk melakukan pencarian data ke textfield gimana ?
ReplyDeleteGan..nanya dong saya udah bikin tabel satu lagi, udah bikin servicenya, serviceimpl, dao, dll..pada saat di jalankan error di HibernateUtil nya gan...Mohon pencerahannya kalau pake 2 tabel apa harus tambah class lagi atau gimana?
ReplyDeleteCoding untuk mencari data di database gimana ya..Misalnya saat menyimpan data ke database saya ingin mencari data dulu misalkan kode (Primary key) apakah kode ini sudah ada apa belum..Mohon bantuannya..Terima kasih..
ReplyDelete