15
Nov
07

Java-Hibernate Codes [technical]

2 Hal yang saya suka menggunakan framework hibernate, Pertama-saya gak perlu bikin database secara langsung, cukup bikin designnya aje pake DBDesigner ➡ bikin class untuk modelnya/setter-getter ➡ bikin file hibernate.cfg.xml yang bakalan ngasih tahu apa aja properties dari app itu skalian ama keterangan koneksi ke database dan nama databasenya supaya databasenya langsung dibuatin secara otomatiiiis 😈 and xml untuk tiap table supaya table-table-nya juga ikut dibuatin. Jadi waktu yang biasa dipake untuk bikin database, bisa dialihkan untuk boker yang laen :mrgreen: . Kedua-codingnya relatif lebih dikit, dan mudah untuk maintainance.

OK dah saya mulai dengan buat hibernate.cfg.xml dulu:


<?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>
        <!-- DB Connection Setting -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/mybook</property>
        <property name="connection.username">dbuser</property>
        <property name="connection.password">dbpass</property>

        <!-- SQL Dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- JDBC Connection pool -->
        <property name="connection.pool_size">1</property>

        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">1800</property>
        <property name="hibernate.c3p0.max_statements">50</property>

        <!-- Enable hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

	<!-- Show the sql query when it executed -->
	<property name="show_sql">true</property>

        <property name="hbm2ddl.auto">update</property>

        <mapping resource="model/Buku.hbm.xml"/>
        <mapping resource="model/Category.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

tahap satu selesai, lanjut ke tahap 2 ➡ skarang saya bikin file xml untuk tiap table. Yang pertama dan terakhir 😯 table Buku [ ex]:


<?xml version="1.0" encoding="UTF-8"?>

<!--
    Document   : Buku.hbm.xml
    Created on : September 3, 2007, 11:29 PM
    Author     : JollkY
    Description:
        Purpose of the document follows.
-->
<!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.Buku" table="BUKU">
        <id name="id" column="ID" type="java.lang.Long">
            <generator class="native"/>
        </id>
        <property name="title" column="TITLE" type="java.lang.String" length="100"/>
        <property name="page" column="PAGE" type="java.lang.Integer" length="5"/>
        <property name="publisher" column="PUBLISHER" type="java.lang.String" length="100"/>
        <property name="writer" column="WRITER" type="java.lang.String" length="100"/>
    </class>
</hibernate-mapping>

Perhatikan code di atas, untuk name=”model.Buku” menyatakan <namaPaket>.<namaClass> sedangkan table=”BUKU” merupakan name tabelnya. Kemudian untuk name=”id” menyatakan nama variable untuk id pada class Buku dalam paket model. Sedangkan column=”TITLE” akan menjadi salah satu nama kolom saat table BUKU diciptakan.

tahap 3 ➡ bikin class model untuk table Buku:


package model;

/**

*

* @author JollkY

*/

public class Buku {

private long id;

private String title;

private int page;

private String publisher;

private String writer;

/**

* Creates a new instance of Buku

*/

public Buku() {

}

public long getId() {

return id;

}

public void setId(long id) {

this.id = id;

}

public String getTitle() {

return title;

}

public void setTitle(String title) {

this.title = title;

}

public int getPage() {

return page;

}

public void setPage(int page) {

this.page = page;

}

[...bleh...bleh...bleh...]

}

tahap 4 ➡ class yang akan berinteraksi dengan DB:


package dao;

import java.util.ArrayList;
import java.util.List;
import model.Buku;
import org.hibernate.Session;

/**
 *
 * @author JollkY
 */
public class BukuDAO {

    /** Creates a new instance of BukuDAO */
    public BukuDAO() {
    }

    public Buku getBuku(long id, Session session) {
        Buku book = (Buku) session.load(Buku.class, id);
        return book;
    }

    public List getBooks(String publisher, Session session) {
        List listBook = new ArrayList();
        listBook = session.createQuery("SELECT buku FROM Buku buku WHERE buku.publisher= :input").setParameter("input", publisher).list();
        return listBook;
    }

}

satu lagi:


package dao;

import org.hibernate.Session;

/**
 *
 * @author JollkY
 */
public class ObjectDAO {

    /** Creates a new instance of ObjectDAO */
    public ObjectDAO() {
    }

    public void save(Object obj, Session sess) {
        sess.save(obj);
    }
    public void delete(Object obj, Session sess) {
        sess.delete(obj);
    }
    public void update(Object obj, Session sess) {
        sess.update(obj);
    }
 }

tahap 5 ➡ class percobaannya:


package tester;

import dao.BukuDAO;
import dao.ObjectDAO;
import java.util.List;
import model.Buku;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author JollkY
 */
public class tester {

    /** Creates a new instance of tester */
    public tester() {
    }

    public static void main(String[] args) {
        SessionFactory sessFactory = new Configuration().configure().buildSessionFactory();
        Session sess = sessFactory.getCurrentSession();
        sess.beginTransaction();
        BukuDAO dao = new BukuDAO();
//        Buku buku = dao.getBuku(1, sess);
//        System.out.print(buku.getTitle()+" | ");
//        System.out.print(buku.getWriter()+" | ");
//        System.out.print(buku.getPublisher()+" | ");
//        System.out.println(buku.getPage());

        List<Buku> listBuku = (List<Buku>)dao.getBooks("Andi Publisher", sess);
        for(Buku b:listBuku) {
            System.out.print(b.getTitle()+" | ");
            System.out.print(b.getWriter()+" | ");
            System.out.print(b.getPublisher()+" | ");
            System.out.println(b.getPage());
        }

//        Buku book = new Buku();
//        book.setId(3);
//        book.setTitle("Fedora Core 4");
//        book.setWriter("Sto");
//        book.setPublisher("Andi Publisher");
//        book.setPage(240);
//        new ObjectDAO().update(book,sess);
        sess.getTransaction().commit();
    }

}

💡 Maap buru” jadi penjelasannya kurang, nanti deh abis kuliah saya edit lagi nih posting. later budy 😈

Advertisements

0 Responses to “Java-Hibernate Codes [technical]”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: