Dear jesustoprural
Here is a piece of code you can use for hibernate.
Step 1: you have to create a class file with the getter and setter of your database table. eg: give below
import java.util.Date;
public class Customer {
private String name;
private Date createDate;
private Long id;
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getName() {
return name;
}
public void setName(String nameCustomer) {
this.name = nameCustomer;
}
public Customer() {
super();
// TODO Auto-generated constructor stub
}
}
Step 2: Create an xml file for this class file. this is an hibernate config file. we have to create hibernate config file for each class file. eg:
Customer.hbm.xml
<?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="Customer"
table="CUSTOMER" //your database table name
lazy="true"
rowid="rowid" dynamic-update="true">
<meta attribute="implement-equals">true</meta>
<id name="id"
type="long"
unsaved-value="null">
<column name="Customer_id"
not-null="true"
unique="true"
index="PK_CUST" />
<generator class="increment"/>
</id>
<property name="name"
column="NAME"
type="string"
not-null="true"
length="30" />
<property name="createDate"
column="CREATED"
type="date"
update="false"
insert="false"
not-null="true"
optimistic-lock="false"
generated="insert" />
</class>
</hibernate-mapping>
Step 3: Create Hibernate.cfg.xml file. Here you have to specify your mysql connection details.
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql-hostname:3306/jbossdb</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</property>
<property name="show_sql">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Step 4: you would also need to add some lib in your project:
asm.jar, commnons-collection-2.1.1.jar, commons-logging-1.0.4.jar, dom4j-1.6.1.jar,hibernate3.jar, hsqldb.jar, xerces.jar
Step 5: now you need a file where you can test your hibernate.
CustomerDisplay.java
import java.util.Date;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class CustomerDisplay{
public static void main(String[] args) throws java.text.ParseException {
CustomerDisplay instance = new CustomerDisplay();
if (args[0].equals("store")) {
String title = args[1];
Date theDate = new Date();
instance.store(title, theDate);
} else if (args[0].equals("list")) {
List events = instance.listEvents();
for (int i = 0; i<events.size(); i++) {
Customer theEvent = (Customer ) events.get(i);
System.out.println(
"Customer " + theEvent.getTitle() + " Time: " + theEvent.getDate());
}
}
System.exit(0);
}
private void store(String title, Date theDate) {
try {
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
Customer theEvent = new Customer ();
theEvent.setName(title);
theEvent.setcreatedDate(theDate);
session.save(theEvent);
tx.commit();
hsqlCleanup(session);
HibernateUtil.closeSession();
} catch (HibernateException e) {
e.printStackTrace();
}
}
private void hsqlCleanup(Session s) {
try {
s.connection().createStatement().execute("SHUTDOWN");
} catch (Exception e) {
}
}
private List listEvents() {
try {
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
List result = session.createQuery("from Customer"). .list();
tx.commit();
hsqlCleanup(session);
HibernateUtil.closeSession();
return result;
} catch (HibernateException e) {
throw new RuntimeException(e.getMessage());
}
}
}
HibernateUtil.java
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil
{
private static final SessionFactory sessionFactory;
static
{
try
{
// Create the SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException
{
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null)
{
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException
{
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
}
that all for implementing hibernate. Enjoy!
|