Menyimpan Objek Java di Database

Untuk menyimpan suatu java object ke table, dibutuhkan field dengan tipe data BLOB, berikut adalah cara menyimpan java object (dalam hal ini javabean) kedalam database, gw pake JDK 6.0 dan MySQL 5. Misalkan ada javabean dengan nama BeanTest (usahakan selalu implements Serializable), dengan struktur dibawah ini :

import java.io.Serializable;

public class BeanTest implements Serializable {

	private String nama;
	private String alamat;

	/**
	 * @return the nama
	 */
	public String getNama() {
		return nama;
	}

	/**
	 * @param nama
	 *            the nama to set
	 */
	public void setNama(String nama) {
		this.nama = nama;
	}

	/**
	 * @return the alamat
	 */
	public String getAlamat() {
		return alamat;
	}

	/**
	 * @param alamat
	 *            the alamat to set
	 */
	public void setAlamat(String alamat) {
		this.alamat = alamat;
	}

}

lalu buat table di database

create database testest;
use testest;

CREATE TABLE IF NOT EXISTS x (
satu varchar(5) NOT NULL DEFAULT ” ,
dua blob ,
PRIMARY KEY (satu)
);

Lalu buatlah class yang akan digunakan untuk berhubungan dengan database, gunakan method setData() untuk memasukkan object ke database, dan getData() untuk mengambil data dari database.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

	public static void main(String[] args) {
		Main main = new Main();

		// simpan data ke database
		main.setData();

		//tarik isi database
		main.getData();
	}

	private void setData() {
		try {

			BeanTest bean = new BeanTest();

			bean.setNama("edwin");
			bean.setAlamat("jakarta");

			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testest", "root", "");
			java.sql.PreparedStatement statement = con.prepareStatement("insert into x values (?,?)");

			statement.setString(1, "00001");
			statement.setBytes(2, toBytes(bean));

			statement.executeUpdate();

			statement.close();
			con.close();
		} catch (Exception ex) {
			Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	private byte[] toBytes(Object object) {
		java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
		try {
			java.io.ObjectOutputStream oos = new java.io.ObjectOutputStream(baos);
			oos.writeObject(object);
			oos.flush();
			oos.close();
		} catch (Exception ioe) {
			ioe.getMessage();
		}

		return baos.toByteArray();
	}

	private void getData() {
		try {
			Class.forName("com.mysql.jdbc.Driver");

			Connection con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/testest", "root", "");
			Statement statement = con.createStatement();
			ResultSet res = statement.executeQuery("select * from x");

			while (res.next()) {
				Object o = toObject(res.getBytes(2));

				if (o instanceof BeanTest) {
					BeanTest beanTest = (BeanTest) o;
					System.out.println(beanTest.getNama());
					System.out.println(beanTest.getAlamat());

				}
			}
			statement.close();
			con.close();
		} catch (Exception ex) {
			Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	private Object toObject(byte[] bytes) {
		Object object = null;
		try {
			object = new java.io.ObjectInputStream(
					new java.io.ByteArrayInputStream(bytes)).readObject();
		} catch (Exception cnfe) {
			cnfe.getMessage();
		}
		return object;
	}
}

sekian dan terima kasih,

Wassalam.

Google+

No Comments

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)