using mysql with hibernate

hi all,

i have used hibernate with hsqldb(database given by default) and it works fine.but when i tried to use it with mysql then i have encountered a problem

exception

org.hibernate.TransactionException: Transaction not successfully started

org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:149)

events.EventManagerServlet.doGet(EventManagerServlet.java:63)

javax.servlet.http.HttpServlet.service(HttpServlet.java:697)

javax.servlet.http.HttpServlet.service(HttpServlet.java:810)

though i have put jar file of mysql in lib directory and changed the driver name in hibernate.cfg.xml.

can any one place some example illustrating the steps involving.

thanks

[744 byte] By [panna_worlda] at [2007-11-26 13:19:04]
# 1
Did you set the dialect correctly?<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
codebooka at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 2
yes i have set dialect as<property name="dialect">org.hibernate.dialect.MySQLDialect</property>still i am getting the same exception.
panna_worlda at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 3
In that case, you'll probably have to post a SMALL piece of example code to demonstrate your problem. Don't forget to use code formatting tags... http://forum.java.sun.com/help.jspa?sec=formatting
codebooka at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 4

this is my enter.jsp

<html>

<head>

<title>Login Page for Hibernate Examples</title>

<body bgcolor="white">

<form method="GET" action='/hibernate/hibernate' >

<table border="0" cellspacing="5">

<tr>

<th align="right">Username :</th>

<td align="left"><input type="text" name="username"></td>

</tr>

<tr>

<th align="right">Password:</th>

<td align="left"><input type="text" name="password"></td>

</tr>

<tr>

<th align="right">Status:</th>

<td align="left"><input type="text" name="status"></td>

</tr>

<tr>

<th align="right">Action to Perform:</th>

<td align="left"><input type="text" name="action"></td>

</tr>

<tr>

<td align="right"><input type="submit" value="Submit"></td>

<td align="left"><input type="reset"></td>

</tr>

</table>

</form>

</body>

</html>

this is form bean Event.java

package events;

import java.util.*;

public class Event {

private Long id;

private String username;

private String password;

private String status;

public Event() {}

public Long getId() {

return id;

}

private void setId(Long id) {

this.id = id;

}

public String getStatus() {

return status;

}

public void setStatus(String status) {

this.status = status;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

}

this is HibernateUtil.java

package util;

import org.hibernate.*;

import org.hibernate.cfg.*;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {

try {

// Create the SessionFactory from hibernate.cfg.xml

System.out.println("session object has been found");

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 SessionFactory getSessionFactory() {

return sessionFactory;

}

}

this is Event.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="events.Event" table="login">

<id name="id" column="login_ID">

<generator class="native"/>

</id>

<property name="username"/>

<property name="password"/>

<property name="status"/>

</class>

</hibernate-mapping>

this is hibernate.cfg.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>

<!-- Database connection settings -->

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>

<property name="connection.url">http://192.168.0.4/inhouse/myadmin</property>

<property name="connection.username">in_house_123</property>

<property name="connection.password">inhouse1234</property>

<!-- JDBC connection pool (use the built-in) -->

<property name="connection.pool_size">1</property>

<!-- SQL dialect -->

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->

<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->

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

<!-- Echo all executed SQL to stdout -->

<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->

<!--<property name="hbm2ddl.auto">create</property>-->

<mapping resource="events/Event.hbm.xml"/>

<!--mapping resource="events/Person.hbm.xml"/-->

</session-factory>

</hibernate-configuration>

this is EventManagerServlet.java

package events;

import util.HibernateUtil;

import org.hibernate.*;

import org.hibernate.Hibernate;

import org.hibernate.criterion.Expression;

import javax.servlet.http.*;

import javax.servlet.ServletException;

import java.io.*;

import java.util.*;

import java.text.SimpleDateFormat;

//import net.sf.hibernate.Expression.*;

public class EventManagerServlet extends HttpServlet {

protected void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

try {

System.out.println("session object has not been found");

// Begin unit of work

HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();

System.out.println("session object has been found");

//Session session = HibernateUtil.getSessionFactory().getCurrentSession();

// Write HTML header

PrintWriter out = response.getWriter();

out.println("<html><head><title>Event Manager</title></head><body>");

// Handle actions

if ( "store".equals(request.getParameter("action")) ) {

String username = request.getParameter("username");

String password = request.getParameter("password");

String status = request.getParameter("status");

if ( "".equals(username) || "".equals(password)|| "".equals(status) ) {

out.println("<b><i>Please enter user name,password or status.</i></b>");

} else {

createAndStoreEvent(username,password,status);

out.println("<b><i>Added event.</i></b>");

}

}

// Print page

printEventForm(out);

listEvents(out);

// Write HTML footer

out.println("</body></html>");

out.flush();

out.close();

// End unit of work

HibernateUtil.getSessionFactory()

.getCurrentSession().getTransaction().commit();

} catch (Exception ex) {

HibernateUtil.getSessionFactory()

.getCurrentSession().getTransaction().rollback();

throw new ServletException(ex);

}

}

private void printEventForm(PrintWriter out) {

out.println("<h2>Add new event:</h2>");

out.println("<form>");

out.println("User Name: <input name='username' length='50'/>
");

out.println("Password: <input name='password' length='50'/>
");

out.println("Status: <input name='status' length='50'/>
");

out.println("<input type='submit' name='action' value='store'/>");

out.println("</form>");

}

private void listEvents(PrintWriter out) {

List result = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(Event.class).list();

if (result.size() > 0) {

out.println("<h2>Events in database:</h2>");

out.println("<table border='1'>");

out.println("<tr>");

out.println("<th>User Name</th>");

out.println("<th>Password</th>");

out.println("<th>Status</th>");

out.println("</tr>");

for (Iterator it = result.iterator(); it.hasNext();) {

Event event = (Event) it.next();

out.println("<tr>");

out.println("<td>" + event.getUsername() + "</td>");

out.println("<td>" + event.getPassword() + "</td>");

out.println("<td>" + event.getStatus() + "</td>");

out.println("</tr>");

}

out.println("</table>");

}

}

protected void createAndStoreEvent(String title, String theDate, String performer) {

Event theEvent = new Event();

theEvent.setUsername(title);

theEvent.setPassword(theDate);

theEvent.setStatus(performer);

HibernateUtil.getSessionFactory()

.getCurrentSession().save(theEvent);

}

}

and then we have set the entry for servlet in web.xml and that i do not think it is necessary to mention that.

thanks

panna_worlda at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 5

> <property name="connection.url">http://192.168.0.4/inhouse/myadmin</property>

Shouldn't your connection URL look more like this...

jdbc:mysql://your.db.host.com/yourDbName

I've never seen an HTTP URL used for a DB connection. I'm no expert, so maybe you are correct, but double-check that just in case.

codebooka at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 6

Nope, this is dead wrong:

<property name="connection.url">http://192.168.0.4/inhouse/myadmin</property>

Look at the docs for the JDBC driver:

.

A million other things wrong with this code, but that's a start.

%

duffymoa at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 7
The URL should look like this:String url ="jdbc:mysql://yourHostNameHere:3306/yourDatabaseNameHere";
duffymoa at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 8
> jdbc:mysql://yourHostNameHere:3306/yourDatabaseNameHereYou can omit the 3306 if you did a default install of MySQL. If you didn't, change the 3306 to whatever port number you have MySQL listening on.
codebooka at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 9
Personally I like leaving it in the URL even if it's the default, if for no other reason than documentation. Why make somebody know what the default port is?%
duffymoa at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 10

thanks but i have not got any fruit full result after making change as suggested by you.

i was wrong at the point of declaring connection url as

jdbc:mysql://192.168.0.4:3306/in_house

but i have got the exception as

org.hibernate.TransactionException: Transaction not successfully started

org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:149)

events.EventManagerServlet.doGet(EventManagerServlet.java:64)

javax.servlet.http.HttpServlet.service(HttpServlet.java:697)

javax.servlet.http.HttpServlet.service(HttpServlet.java:810)

if you have any example of it then please forward it

thanks

panna_worlda at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...
# 11

Hi There

Please find the code that i have posted here..........

hybernate.dialect=

net.sf.hibernate.dialect.MySQLDialect

hibernate.connection.driver_class=

com.mysql.jdbc.Driver

hybernate.connection.url=

jdbc:mysql://localhost/hiberdemo

hibernate.connection.username=

hibernate.connection.password=

*************************************************

hibernate.cfg.xml

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

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="connection.driver">

com.mysql.jdbc.Driver

</property>

<property name="connection">

jdbc:mysql://localhost/players

</property>

<property name="dialect">

net.sf.hibernate.dialect.MySQLDialect

</property>

</session-factory>

</hibernate-configuration>

*************************************************

public class player

{

private Stringname;

private Stringplace;

private intid;

public player() {}

public player(String a,String b)

{

name=a;

place=b;

}

public String getName()

{

return name;

}

public void setName(String a)

{

name = a;

}

public String getPlace()

{

return place;

}

public void setPlace(String b)

{

place = b;

}

public int getId()

{

return id;

}

public void setId(int s)

{

id = s;

}

}

*****************************************

This is just the usual JavaBean file. We must strictly follow the JavaBean convention. It must have a public no-args constructor.

It has another constructor, too.

****************************************

We can easily compile this file to get player.class. This class will be referred to in the mapping document, known by the name

player.hbm.xml, given below.

--

// c:\hiberdemo\player.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 2.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>

<class name="player" table="player">

<id name="id" type="int" unsaved-value="null">

<column name="ID" sql-type="int" not-null="true" />

<generator class="hilo"/>

</id>

<property name="name" type="string"/>

<property name="place" type="string"/>

</class>

</hibernate-mapping>

****************************************

import java.io.*;

import java.util.*;

import net.sf.hibernate.*;

import net.sf.hibernate.cfg.*;

In the constructor itself, we have to initialize the SessionFactory, using try-catch block.

SessionFactoryfactory;

try

{

Configurationcfg =

new Configuration();

cfg.addClass(player.class);

factory = cfg.buildSessionFactory();

area1.setText("factory ready");

} catch(Exception e1){

area1.setText(""+e1);

}

-

The code creates a new configuration object and tries to load the mapping document for the class specified in the addClass() method.

To build a Session object a session factory object needs to be instantiated from the Configuration object. The constructor assumes there is a class attribute defined as follows:

factory =null;

The buildSessionFactory() method builds a factory based on the specifics of mapping document processed by Configuration object.

*************************************************************

The code for adding is

String a = text1.getText();// name

String b = text2.getText();// place

try

{

Sessionsession = factory.openSession();

Transactiontx = null;

tx = session.beginTransaction();

playerplayer1 = new player(a,b);

session.save(player1);

tx.commit();

session.flush();

session.close();

area1.setText("added");

}catch(Exception e1) {

area1.setText(""+e1);

}

*************************************

The above steps are very easy to comprehend. A new object is created in memory with the given name and place and is persisted in the player table. The required SQL is automatically generated by Hibernate and carried out.

And the rest is easy........... i guess u should be able to sort it out

Thanks and Regards

Naveen M

Novice_inJAVAa at 2007-7-7 17:45:15 > top of Java-index,Java Essentials,New To Java...