hibernate Posts

A Weird Hibernate Exception : org.hibernate.ObjectNotFoundException: No row with the given identifier exists

Today i met a weird hibernate exception, somehow it show that my User object does not exists. A little bit weird because i’m querying Comment tables, but the exceptions show “object user does not exist”.

	A Weird Hibernate Error : org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.edw.entity.User#anonymousUser]
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.edw.entity.User#anonymousUser]
	at org.hibernate.impl.SessionFactoryImpl$1.handleEntityNotFound(SessionFactoryImpl.java:377)
	at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:145)
	at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:195)
	at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:103)
	at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:878)
	at org.hibernate.impl.SessionImpl.internalLoad(SessionImpl.java:846)
	at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:557)
	at org.hibernate.type.EntityType.resolve(EntityType.java:379)
	at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:120)

After some minutes digging on my sourcecode, i found out that javabean Comment has a @ManyToOne (Hibernate annotation for many to one relationship) to javabean User. Too bad one Comment object, still has a foreign key to a deleted User object.

This is my previous User class and Comment class, the main culprit is on line 30.

package com.edw.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

@Entity
@Table(name="tbl_comment")
public class Comment implements Serializable {

	@Id
	@GeneratedValue
	private Long id;
	
	@Temporal(TemporalType.TIMESTAMP)
	private Date timestamp;
	
	private String content;
		
	@ManyToOne
	private User user;
		
	@ManyToOne
	private News news;

	public Long getId() {
		return id;
	}
	// other setter and getter
}
package com.edw.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="tbl_user")
public class User implements Serializable {

	@Id
    private String username;
    private String password;
    private Boolean status;
    
    private String email;
    private String name;
    private String address;
    private String city;
    private String job;
    private String about;
    private String relationship;
    private String privacy;
    
    private String role;
    
    private String tokenRegistration;
    private String tokenForgotPassword;
    
    public User() {}
    public User(String username) {
    	this.username = username;
    }   	
}

The workaround is by adding @NotFound annotation to ignore the condition when Hibernate unable to find the User class.

package com.edw.entity;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

@Entity
@Table(name="tbl_comment")
public class Comment implements Serializable {

	@Id
	@GeneratedValue
	private Long id;
	
	@Temporal(TemporalType.TIMESTAMP)
	private Date timestamp;
	
	private String content;
	
	@NotFound(action=NotFoundAction.IGNORE)
	@ManyToOne
	private User user;
	
	@NotFound(action=NotFoundAction.IGNORE)
	@ManyToOne
	private News news;

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
}

Hope it helped others, have fun ;-)

Google+

Integrating BCrypt Hashing With Hibernate Framework

In this example, im trying to simulate a simple login to MySQL database. Usually i hash password value using MD5, but now im trying to do hashing using BCrypt Algorithm. Im using a simple java BCrypt class downloaded from here.

First as always, a simple table and row.

CREATE TABLE `users` (
  `username` varchar(20) NOT NULL DEFAULT '',
  `pwd` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`username`)
)

insert into `users`(`username`,`pwd`) values ('edwin','$2a$12$bUwElzXYO116G6x.fLm5FOAJNB46R0974sAh2TQumJei4ia.x0YPy');

Next is creating a simple java class and xml to represent database tables.

package com.edw.bean;

public class Users  implements java.io.Serializable {

     private String username;
     private String pwd;

    public Users() {
    }

	// other setter and getter
}
<?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="com.edw.bean.Users" table="users" catalog="test">
        <id name="username" type="string">
            <column name="username" length="20" />
            <generator class="assigned" />
        </id>
        <property name="pwd" type="string">
            <column name="pwd" length="80" />
        </property>
    </class>
</hibernate-mapping>

Next is my hibernate.cfg.xml configuration

<?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/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">****</property>
    <mapping resource="com/edw/bean/Users.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

And my java class to load hibernate.cfg.xml

package com.edw.util;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {           
            sessionFactory = 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;
    }
}

And this is my Main java class,

package com.edw.main;

import com.edw.bean.Users;
import com.edw.util.BCrypt;
import com.edw.util.HibernateUtil;
import org.apache.log4j.Logger;
import org.hibernate.Session;

public class Main {
    
    private static Logger logger = Logger.getLogger(Main.class );
    
    private Boolean startApp(String username, String password) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            Users user = (Users)session.createQuery("from Users where username = :username")
                    .setString("username", username)
                    .uniqueResult();      
            // compare password with database's encrypted password
            if(BCrypt.checkpw(password, user.getPwd()))
                return true;
            return false;
        } catch (Exception e) {
            logger.error(e,e);
        } finally {            
            session.close();
        }
        return false;
    }
    
    private String hashPassword(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt(12));
    }
    
    public static void main(String[] args) {
        Main main = new Main();
        boolean success = main.startApp("edwin", "12345");
        if(success)
            logger.debug("Password is Right");
        else
            logger.debug("Password is Wrong");
        
        // simulate 10 hashed string password
        for (int i = 0; i < 10; i++) {
            logger.debug(main.hashPassword("12345"));
        }        
    }
}

This is my Netbeans project structure,

And this is my Netbean’s console

Google+

How to Create A Java Class Performance Test Using JMeters AbstractJavaSamplerClient

JMeter is a very powerfull tools to do performance testing. In this tutorial, im going to simulate a heavy load on a java object to test its strength and performance testing. My java class is very simple, only an ordinary java class to do inserts into mysql database using Hibernate framework.

first is a sample database and a table

CREATE DATABASE test;
USE test;
CREATE
    TABLE student
    (
        id INT NOT NULL AUTO_INCREMENT,
        studentname VARCHAR(60) NOT NULL,
        PRIMARY KEY (id)
    );

a java class and xml as representation for database’s table

package com.edw.bean;

public class Student implements java.io.Serializable {

    private Integer id;
    private String studentname;

    public Student() {
    }

    public Student(String studentname) {
       this.studentname = studentname;
    }
	
	// other setter and getter
<?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="com.edw.bean.Student" table="student" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="studentname" type="string">
            <column name="studentname" length="60" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

this is my Hibernate main configuration xml

<?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/test</property>
    <property name="hibernate.connection.username">root</property>
	<property name="hibernate.connection.password">xxxxxx</property>
    <property name="hibernate.connection.autocommit">true</property>
    <mapping resource="com/edw/bean/Student.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

and my java class to load Hibernate’s configuration

package com.edw.hbm;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * @author edw
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = 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;
    }
}

This is my tested java class, it has to extends AbstractJavaSamplerClient so the jmeter application can test it

package com.edw.test;

import com.edw.bean.Student;
import com.edw.hbm.HibernateUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *  com.edw.test.StudentStressTest
 *
 *  @author edw
 */
public class StudentStressTest extends AbstractJavaSamplerClient {

    private Map<String, String> mapParams = new HashMap<String, String>();
    private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public StudentStressTest() {
        super();
    }

    @Override
    public void setupTest(JavaSamplerContext context) {
        for (Iterator<String> it = context.getParameterNamesIterator(); it.hasNext();) {
            String paramName =  it.next();
            mapParams.put(paramName, context.getParameter(paramName));
        }
    }

    public SampleResult runTest(JavaSamplerContext context) {
        SampleResult result = new SampleResult();

        try {

            JMeterVariables vars = JMeterContextService.getContext().getVariables();
            vars.put("demo", "demoVariableContent");

            result.sampleStart();

            Student student = new Student();
            student.setStudentname(mapParams.get("name")+" "+new Date().getTime());
            Session session = sessionFactory.openSession();
            session.save(student);
            session.flush();
            session.close();

            result.sampleEnd();

            
            result.setSuccessful(true);
            result.setSampleLabel("SUCCESS: " + student.getStudentname());

        } catch (Throwable e) {
            result.sampleEnd();
            result.setSampleLabel("FAILED: '" + e.getMessage() + "' || " + e.toString());
            result.setSuccessful(false);

            e.printStackTrace();
            System.out.println("\n\n\n");
        }

        return result;
    }

    @Override
    public Arguments getDefaultParameters() {

        Arguments params = new Arguments();

        params.addArgument("name", "edw");

        return params;
    }
}

Next is build your project into jar and put it into jmeter’s path ( \lib\ext ), dont forget to copy your application library such as hibernate3.jar.
If you open your JMeter ui, you can see your java class on Add > Sampler > Java Request. You can see the results sumamry on tab summary report.

This is my Netbeans project structure, and my jmeter configuration.

Have fun working with JMeter :)

Google+

A Simple Hibernate Caching Example using OSCache and EHCache

In this example im trying to create a simple application using Hibernate’s caching feature. What is cache anyway? A cache is designed to reduce traffic between your application and the database by conserving data already loaded from the database and put it whether in memory or in file. Database access is necessary only when retrieving data that is not currently available in the cache. So basically not all queries are taken from database, but from cache instead.

Hibernate use EHCache for default caching, but now im trying to demonstrate both OSCache and EHCache caching library. But you can only use one of it at one time. Both of them only differ in caching configuration, but the rest are still the same.

First is a simple sql file, a java bean and its hibernate xml configuration

CREATE
    TABLE matakuliah
    (
        kodematakuliah VARCHAR(10) NOT NULL,        
        namamatakuliah VARCHAR(20),
        PRIMARY KEY (kodematakuliah)
    )
    ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT
INTO
    matakuliah
    (
        kodematakuliah,        
        namamatakuliah
    )
    VALUES
    (
        '123',        
        'ccc'
    );
package com.edw.bean;

public class Matakuliah  implements java.io.Serializable {

     public class Matakuliah  implements java.io.Serializable {

     private String kodematakuliah;
     private String namamatakuliah;

    public Matakuliah() {
    }

    public Matakuliah(String kodematakuliah) {
        this.kodematakuliah = kodematakuliah;
    }
    public Matakuliah(String kodematakuliah, String namamatakuliah) {
       this.kodematakuliah = kodematakuliah;      
       this.namamatakuliah = namamatakuliah;
    }
   
    // other setters and getters   
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class catalog="kampus" name="com.edw.bean.Matakuliah" table="matakuliah">

    <!-- caching configuration -->
    <cache usage="read-write" />
    
    <id name="kodematakuliah" type="string">
      <column length="10" name="kodematakuliah"/>
      <generator class="assigned"/>
    </id>
      
    <property name="namamatakuliah" type="string">
      <column length="20" name="namamatakuliah"/>
    </property>       
  </class>
</hibernate-mapping>

please take a look at line 7, im using read-write because my data sometimes get updated. If you are planning to have static data that never changes, use read-only.

Next is registering EhCacheProvider on hibernate.cfg.xml file

<?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:3307/kampus</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.autocommit">true</property>
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <mapping resource="com/edw/bean/Matakuliah.hbm.xml"/>    
  </session-factory>
</hibernate-configuration>

create a java file to load your hibernate configuration file

package com.edw.util;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HiberUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

and dont forget your ehcache.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<!--
    caching configuration
-->
<ehcache>
    <defaultCache
        maxElementsInMemory="10"
        eternal="false"
        timeToIdleSeconds="0"
        timeToLiveSeconds="0"
        overflowToDisk="false"/>
</ehcache>

and this is my java file to test hibernate’s caching ability

package com.edw.main.caching;

import com.edw.bean.Matakuliah;
import com.edw.util.HiberUtil;
import java.util.Date;
import org.hibernate.Session;

public class CachingMain {

    public CachingMain() {
    }   

    /**
     *  do some repeated queries for table Matakuliah
     *  query results are taken from cache memory instead of database     
     */
    private void withCache() {

        Session session = null;
        try {            
            for (int i = 0; i < 3; i++) {

                // open session
                session = HiberUtil.getSessionFactory().openSession();                

                // time needed
                long now = new Date().getTime();

                // select
                Matakuliah matakuliah = (Matakuliah)session.load(Matakuliah.class, "123");

                // print
                System.out.println("matakuliah "+matakuliah.getNamamatakuliah());
                System.out.println("Time : " + (new Date().getTime() - now) + " ms");

                // sleep for 3seconds
                Thread.sleep(3000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }

    public static void main(String[] args) {
        CachingMain main = new CachingMain();
        main.withCache();
    }
}

you can see in your console, if you use log4j, this is what happen when Hibernate is querying from cache instead of database

DEBUG org.hibernate.impl.SessionImpl:220 - opened session at timestamp: 5364197853302784
DEBUG org.hibernate.jdbc.ConnectionManager:404 - aggressively releasing JDBC connection
DEBUG org.hibernate.impl.SessionImpl:832 - initializing proxy: [com.edw.bean.Matakuliah#123]
DEBUG org.hibernate.cache.EhCache:68 - key: com.edw.bean.Matakuliah#123
DEBUG org.hibernate.engine.StatefulPersistenceContext:790 - initializing non-lazy collections
matakuliah ccc
Time : 1 ms

Moving from EhCache to OsCache is very simple, all you have to do is replacing 1 line in your xml file, and adding an oscache.properties file.

<?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:3307/kampus</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.autocommit">false</property>
    <property name="hibernate.cache.use_second_level_cache">true</property>
    <property name="hibernate.cache.use_query_cache">true</property>
    <property name="hibernate.cache.provider_class">org.hibernate.cache.OSCacheProvider</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <mapping resource="com/edw/bean/Matakuliah.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

and this is my oscache.properties

cache.capacity=1000
cache.path=c:\\cache\\
cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener

this is what happen on my Netbeans console when im using OsCache

DEBUG org.hibernate.impl.SessionImpl:220 - opened session at timestamp: 5364208706285568
DEBUG org.hibernate.jdbc.ConnectionManager:404 - aggressively releasing JDBC connection
DEBUG org.hibernate.impl.SessionImpl:832 - initializing proxy: [com.edw.bean.Matakuliah#123]
DEBUG com.opensymphony.oscache.base.algorithm.AbstractConcurrentReadCache:694 - get called (key=com.edw.bean.Matakuliah#123.com.edw.bean.Matakuliah)
DEBUG org.hibernate.engine.StatefulPersistenceContext:790 - initializing non-lazy collections
matakuliah ccc
Time : 1 ms

This is my project structure,

Hope it can help others. Have fun. (*)

Google+

[Tutorial] Upload File dan Isi Form Sederhana ke Database dengan JSP

Karena banyak pertanyaan terkait insert isi form ke database dan upload image / file ke server, akhirnya gw memutuskan untuk nulis ini di blog gw, kali aja suatu saat ada yang nanya lagi.

Disini gw bikin aplikasi sederhana dengan 1 input text dan 1 input untuk upload file, semua yang diinput akan masuk ke database. Khusus untuk si file akan masuk path relatifnya (image/NamaImageYangDiUpload). Gw pakek library apache commons fileupload, commons io dan Hibernate framework (pake query sql biasa juga bisa tapi gw males aja, ahhahaaa).

oke langsung aja, gw bikin table sederhana banget,

CREATE TABLE upload
(
    id INT NOT NULL AUTO_INCREMENT,
    uploadBy VARCHAR(20) NOT NULL,
    imagePath VARCHAR(200) NOT NULL,
    PRIMARY KEY (id)
)

java bean ma hbm.xml-nya

package com.baculsoft.bean;

public class Upload  implements java.io.Serializable {


     private Integer id;
     private String uploadBy;
     private String imagePath;

    public Upload() {
    }

    public Upload(String uploadBy, String imagePath) {
       this.uploadBy = uploadBy;
       this.imagePath = imagePath;
    }
   
    // other setter and getter

    @Override
    public String toString() {
        return "Upload{" + "id=" + id + " uploadBy=" + uploadBy + " imagePath=" + imagePath + '}';
    }

}
<?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="com.baculsoft.bean.Upload" table="upload" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="uploadBy" type="string">
            <column name="uploadBy" length="20" not-null="true" />
        </property>
        <property name="imagePath" type="string">
            <column name="imagePath" length="50" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

lalu hibernate.cfg.xml buat handle koneksi ke database

<?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/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.connection.autocommit">true</property>
    <mapping resource="com/baculsoft/bean/Upload.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

dan file java buat ngeload hibernate.cfg.xml

package com.baculsoft.hbm;


import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author edw
 */
public class HiberUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

nah ini adalah JSP gw, coba perhatiin kalo gw punya 2 input type. 1 buat input dengan type text 1 lagi buat input type file.

<%-- 
    Document   : index
    Created on : Jan 2, 2011, 9:34:34 PM
    Author     : edw
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>        
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <form action="upload" method="POST" enctype="multipart/form-data">
            Input Your Name : <input type="text" name="uploadBy" />
            <br />
            Select file : <input type="file" name="fileSelect" />
            <br />
            <input type="submit" />
        </form>
    </body>
</html>

nah, yang rada ribet ada disini. Ini adalah servlet yg gw bikin khusus buat handle transfer file dari client ke server dan save path+nama file tersebut ke database. Method yg gw gunakan untuk insert ke database ada di line 90.

package com.baculsoft.servlet;

import com.baculsoft.bean.Upload;
import com.baculsoft.hbm.HiberUtil;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.hibernate.Session;

public class UploadServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(UploadServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String uploadTo = getServletContext().getRealPath("/") + "image/";

        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            // no multipart form
            if (!isMultipart) {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet UploadServlet</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>No Multipart Files</h1>");
                out.println("</body>");
                out.println("</html>");
            }
            // multipart form
            else {
                // Create a new file upload handler
                ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

                // parse requests
                List<FileItem> fileItems = servletFileUpload.parseRequest(request);

                // open session factory
                Session session = HiberUtil.getSessionFactory().openSession();

                // prepare upload bean
                Upload upload = new Upload();

                // Process the uploaded items
                for (FileItem fileItem : fileItems) {                    
                    
                    // a regular form field
                    if (fileItem.isFormField()) {

                        // disini sama dengan nama input text field di index.jsp yaitu "uploadBy"
                        if(fileItem.getFieldName().equalsIgnoreCase("uploadBy")){
                            upload.setUploadBy(fileItem.getString());
                        }
                    }
                    // upload field
                    else {
                        String fileName = fileItem.getName();
                        File fileTo = new File(uploadTo + fileName);
                        fileItem.write(fileTo);

                        out.println("<html>");
                        out.println("<head>");
                        out.println("<title>Servlet UploadServlet</title>");
                        out.println("</head>");
                        out.println("<body>");
                        out.println("<h1> success write to " + fileTo.getAbsolutePath() + "</h1>");
                        out.println("</body>");
                        out.println("</html>");

                        // set uploaded file's location
                        upload.setImagePath("image/"+fileName);

                    }
                }

                session.save(upload);

                session.flush();
                session.close();

                logger.debug("success");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } finally {
            out.close();
        }
    }
   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

berikut adalah log4j.properties gw

# Global logging configuration
log4j.rootLogger=DEBUG,stdout

# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%c{1}] %-5p %c:%L - %m%n

ini struktur project netbeans gw,

ini lib yg gw pakek

File yang berhasil terupload akan disimpan di folder image/. Disini gw coba upload 2 kali.

dan ini isi database gw

Silahkan dicoba masing-masing yeh, :-[

Google+