I am just stepping into Hibernate. I tried my first example provided at
http://www.tutcity.com/view/hibernate-example-using-hibernate-tools.19730.htmlMy configuration file is
Code:
<?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.password">pwd</property>
<property name="hibernate.connection.url">http://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="com/vaannila/course/Course.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The mapping file is
Code:
<?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.vaannila.course.Course" table="COURSES">
<meta attribute="class-description">
This class represents a row in the COURSES table
</meta>
<id name="courseId" type="long" column="COURSE_ID">
<generator class="native"></generator>
</id>
<property name="courseName" type="string" column="COURSE_NAME"
not-null="true" />
</class>
</hibernate-mapping>
And my main mthod is
Code:
package com.vaannila.course;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.vaannila.util.HibernateUtil;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Main obj = new Main();
Long courseId1 = obj.saveCourse("Physics");
Long courseId2 = obj.saveCourse("Chemistry");
Long courseId3 = obj.saveCourse("Maths");
}
public Long saveCourse(String courseName)
{
// gets the session
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
Long courseId = null;
try {
transaction = session.beginTransaction();
Course course = new Course();
course.setCourseName(courseName);
courseId = (Long) session.save(course);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return courseId;
}
}
When i run this code, i get a NullPointerException at the point
transaction = session.beginTransaction(); eventhough session is not null.
What could be the problem?
I am using MySQL.