Need help with Hibernate? Read this first:
http://www.hibernate.org/ForumMailingli ... AskForHelp
Hibernate version:
hibernate 3.0
Mapping documents:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.inetmon.jn.addrbook.domainName">
<class name="DomainName"
table="Domain"
polymorphism="implicit"
>
<id name="mac" type="java.lang.String" unsaved-value="null" >
<column name="MAC" sql-type="VARCHAR" not-null="false"/>
<generator class="assigned"/>
</id>
<property name="ipv6" column="ipv6" type="java.lang.String"/>
<property name="domainName" column="domainName" type="java.lang.String"/>
</class>
<class
name="Address"
table="ADDR"
polymorphism="implicit"
>
<id name="mac" type="java.lang.String" unsaved-value="null" >
<column name="MAC" sql-type="VARCHAR"
not-null="false"/>
<generator class="select"/>
</id>
<property name="ipv4" column="IPv4" type="java.lang.String" />
<property name="ipv6" column="IPv6" type="java.lang.String"/>
</class>
</hibernate-mapping>
Code between sessionFactory.openSession() and session.close():
package com.inetmon.jn.addrbook.domainName.util;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Basic Hibernate helper class, handles SessionFactory, Session and Transaction.
* <p>
* Uses a static initializer for the initial SessionFactory creation
* and holds Session and Transactions in thread local variables. All
* exceptions are wrapped in an unchecked InfrastructureException.
*/
public class HibernateUtil {
private static Log log = LogFactory.getLog(HibernateUtil.class);
private static Configuration configuration;
private static SessionFactory sessionFactory;
private static final ThreadLocal threadSession = new ThreadLocal();
private static final ThreadLocal threadTransaction = new ThreadLocal();
private static final ThreadLocal threadInterceptor = new ThreadLocal();
// Create the initial SessionFactory from the default configuration files
static {
try {
configuration = new Configuration();
sessionFactory = configuration.configure().buildSessionFactory();
// We could also let Hibernate bind it to JNDI:
// configuration.configure().buildSessionFactory()
} catch (Throwable ex) {
// We have to catch Throwable, otherwise we will miss
// NoClassDefFoundError and other subclasses of Error
log.error("Building SessionFactory failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
/**
* Returns the SessionFactory used for this static class.
*
* @return SessionFactory
*/
public static SessionFactory getSessionFactory() {
/* Instead of a static variable, use JNDI:
SessionFactory sessions = null;
try {
Context ctx = new InitialContext();
String jndiName = "java:hibernate/HibernateFactory";
sessions = (SessionFactory)ctx.lookup(jndiName);
} catch (NamingException ex) {
throw new InfrastructureException(ex);
}
return sessions;
*/
return sessionFactory;
}
/**
* Returns the original Hibernate configuration.
*
* @return Configuration
*/
public static Configuration getConfiguration() {
return configuration;
}
/**
* Rebuild the SessionFactory with the static Configuration.
*
*/
public static void rebuildSessionFactory()
throws InfrastructureException {
synchronized(sessionFactory) {
try {
sessionFactory = getConfiguration().buildSessionFactory();
} catch (Exception ex) {
throw new InfrastructureException(ex);
}
}
}
/**
* Rebuild the SessionFactory with the given Hibernate Configuration.
*
* @param cfg
*/
public static void rebuildSessionFactory(Configuration cfg)
throws InfrastructureException {
synchronized(sessionFactory) {
try {
sessionFactory = cfg.buildSessionFactory();
configuration = cfg;
} catch (Exception ex) {
throw new InfrastructureException(ex);
}
}
}
/**
* Retrieves the current Session local to the thread.
* <p/>
* If no Session is open, opens a new Session for the running thread.
*
* @return Session
*/
public static Session getSession()
throws InfrastructureException {
Session s = (Session) threadSession.get();
try {
if (s == null) {
log.debug("Opening new Session for this thread.");
if (getInterceptor() != null) {
log.debug("Using interceptor: " + getInterceptor().getClass());
s = getSessionFactory().openSession(getInterceptor());
} else {
s = getSessionFactory().openSession();
}
threadSession.set(s);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
return s;
}
/**
* Closes the Session local to the thread.
*/
public static void closeSession()
throws InfrastructureException {
try {
Session s = (Session) threadSession.get();
threadSession.set(null);
if (s != null && s.isOpen()) {
log.debug("Closing Session of this thread.");
s.close();
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
/**
* Start a new database transaction.
*/
public static void beginTransaction()
throws InfrastructureException {
Transaction tx = (Transaction) threadTransaction.get();
try {
if (tx == null) {
log.debug("Starting new database transaction in this thread.");
tx = getSession().beginTransaction();
threadTransaction.set(tx);
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
/**
* Commit the database transaction.
*/
public static void commitTransaction()
throws InfrastructureException {
Transaction tx = (Transaction) threadTransaction.get();
try {
if ( tx != null && !tx.wasCommitted()
&& !tx.wasRolledBack() ) {
log.debug("Committing database transaction of this thread.");
tx.commit();
}
threadTransaction.set(null);
} catch (HibernateException ex) {
rollbackTransaction();
throw new InfrastructureException(ex);
}
}
/**
* Commit the database transaction.
*/
public static void rollbackTransaction()
throws InfrastructureException {
Transaction tx = (Transaction) threadTransaction.get();
try {
threadTransaction.set(null);
if ( tx != null && !tx.wasCommitted() && !tx.wasRolledBack() ) {
log.debug("Tyring to rollback database transaction of this thread.");
tx.rollback();
}
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
} finally {
closeSession();
}
}
/**
* Reconnects a Hibernate Session to the current Thread.
*
* @param session The Hibernate Session to be reconnected.
*/
public static void reconnect(Session session)
throws InfrastructureException {
try {
session.reconnect();
threadSession.set(session);
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
/**
* Disconnect and return Session from current Thread.
*
* @return Session the disconnected Session
*/
public static Session disconnectSession()
throws InfrastructureException {
Session session = getSession();
try {
threadSession.set(null);
if (session.isConnected() && session.isOpen())
session.disconnect();
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
return session;
}
/**
* Register a Hibernate interceptor with the current thread.
* <p>
* Every Session opened is opened with this interceptor after
* registration. Has no effect if the current Session of the
* thread is already open, effective on next close()/getSession().
*/
public static void registerInterceptor(Interceptor interceptor) {
threadInterceptor.set(interceptor);
}
private static Interceptor getInterceptor() {
Interceptor interceptor =
(Interceptor) threadInterceptor.get();
return interceptor;
}
public static void setConnectionProperties(Properties props) {
// TODO Auto-generated method stub
}
}
Full stack trace of any exception that occurs:
java.lang.NullPointerException
at com.inetmon.jn.addrbook.domainName.test.DomainTest.testInsertAddr(DomainTest.java:94)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:154)
at com.inetmon.jn.addrbook.domainName.test.TestCase.runTest(TestCase.java:18)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:474)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:342)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:194)
Name and version of the database you are using:
hsqldb 1.7.3
The generated SQL (show_sql=true):
create table Domain (
MAC VARCHAR,
ipv6 varchar(255),
domainName varchar(255),
primary key (MAC)
)
Debug level Hibernate log excerpt:
/**
* Class to test domain Name resolver
*
*/
public class DomainTest extends TestCase{
private DomainName dn;
private DomainNameDAO dno;
private String ipv6;
private String domainName;
private char cr;
int number = 10;
private final Random rnd = new Random();
Session s = HibernateUtil.getSession();
InetExample ie =new InetExample();
private String name;
ArrayList addrList = new ArrayList();
/** constructor */
public DomainTest(String x) {
super(x);
}
/** create test suite */
public static Test suite() {
return new TestSuite(DomainTest.class);
}
/** function to get char 0-9 and A-F*/
public char getNextChar() {
int cr = 0;
while (!((cr >= 48 && cr < 57) || (cr >= 65 && cr < 70))) {
cr = rnd.nextInt(70);
}
return (char) cr;
}
/** initialize data */
private void initData() {
for (int i = 0; i < number; i++) {
String mac = new String(getNextChar() + "")
+ new String(getNextChar() + "-");
ipv6 += new String(getNextChar() + "")
+ new String(getNextChar() + "-");
ipv6 += new String(getNextChar() + "")
+ new String(getNextChar() + "-");
ipv6 += new String(getNextChar() + "")
+ new String(getNextChar() + "-");
mac += new String(getNextChar() + "")
+ new String(getNextChar() + "-");
mac += new String(getNextChar() + "")
+ new String(getNextChar() + "");
Address addr = new Address(mac, "10.207.130.5", "10.207.128.3");
addrList.add(addr);
}
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
}
/** insert data */
public void testInsertAddr() throws Exception {
initData();
dno.save(domainName,s);
}
public void testRetrieveRecord() throws Exception {
initData();
dno.load(ipv6,s);
}
public void testDeleteRecord() throws Exception {
initData();
dno.delete(ipv6,s);
}
}
Anyone know how to solve java.lang.NullPointerException Error!!!!! Thank you very much!!!!!