-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 
Author Message
 Post subject: HelloWorld, error with Message Annotations example
PostPosted: Sat Apr 28, 2007 9:10 am 
Newbie

Joined: Thu Apr 19, 2007 8:55 pm
Posts: 4
I'm in section 2.2, and I've modified the HelloWorld example to use annotations instead of Message.hbm.xml. I believe I've made the needed changes to files as described in the book, but I get an error that I haven't been able solve.



Here are the runtime errors, and the changes I've made to files.

[b]Hibernate version: 3.2

Name and version of the database you are using: HSQLDB server 1.8.0

output
-------
Buildfile: build.xml

compile:

copymetafiles:

run:
[java] 08:40:32,503 WARN UserSuppliedConnectionProvider:23 - No connection properties specified - the user must supply JDBC connections
[java] Exception in thread "main" java.lang.ExceptionInInitializerError
[java] at persistence.HibernateUtil.<clinit>(Unknown Source)
[java] at hello.HelloWorld.main(Unknown Source)
[java] Caused by: org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
[java] at org.hibernate.dialect.DialectFactory.determineDialect(DialectFactory.java:57)
[java] at org.hibernate.dialect.DialectFactory.buildDialect(DialectFactory.java:39)
[java] at org.hibernate.cfg.SettingsFactory.determineDialect(SettingsFactory.java:409)
[java] at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:119)
[java] at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1933)
[java] at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1216)
[java] ... 2 more
[java] Java Result: 1

BUILD SUCCESSFUL


build.xml changes
--------------------

<!-- Export the database schema -->
<target name="schemaexport" depends="compile, copymetafiles"
description="Exports a generated schema to DB and file">


<hibernatetool destdir="${basedir}">
<classpath path="${build.dir}"/>
<annotationconfiguration
configurationfile="${build.dir}/hibernate.cfg.xml"/>


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-3.0.dtd">

<hibernate-configuration>
<session-factory>

<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="hibernate.connection.username">sa</property>


<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>

<!-- SQL to stdout logging
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
-->



<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<mapping class="hello.Message"/>

</session-factory>
</hibernate-configuration>

Message.java
---------------

package hello;

import javax.persistence.*;

@Entity
@Table(name = "MESSAGES")
public class Message {

@Id @GeneratedValue
@Column(name = "MESSAGE_ID")
private Long id;

@Column(name = "MESSAGE_TEXT")
private String text;

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "NEXT_MESSAGE_ID")
private Message nextMessage;

Message() {}

public Message(String text) {
this.text = text;
}

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

public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}

public Message getNextMessage() {
return nextMessage;
}
public void setNextMessage(Message nextMessage) {
this.nextMessage = nextMessage;
}
}

HibernateUtil.java
---------------------

import org.hibernate.*;
import org.hibernate.cfg.*;

/**
* Startup Hibernate and provide access to the singleton SessionFactory
*/
public class HibernateUtil {

private static SessionFactory sessionFactory;

static {
try {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass(hello.Message.class);
sessionFactory = cfg.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
// Alternatively, we could look up in JNDI here
return sessionFactory;
}

public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}

HelloWorld.java
-----------------
package hello;

import org.hibernate.*;
import persistence.*;
import java.util.*;

public class HelloWorld {

public static void main(String[] args) {

// ############################################################################

// First unit of work
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();

Message message = new Message("Hello World");
session.save(message);

tx.commit();
session.close();

// ############################################################################

// Second unit of work
Session secondSession = HibernateUtil.getSessionFactory().openSession();
Transaction secondTransaction = secondSession.beginTransaction();

List messages =
secondSession.createQuery("from Message m order by m.text asc").list();

System.out.println( messages.size() + " message(s) found:" );

for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
Message loadedMsg = (Message) iter.next();
System.out.println( loadedMsg.getText() );
}

secondTransaction.commit();
secondSession.close();

// ############################################################################

// Third unit of work
Session thirdSession = HibernateUtil.getSessionFactory().openSession();
Transaction thirdTransaction = thirdSession.beginTransaction();

// message.getId() holds the identifier value of the first message
Message loadedMessage = (Message) thirdSession.get( Message.class, message.getId());
loadedMessage.setText( "Greetings Earthling" );
loadedMessage.setNextMessage(
new Message( "Take me to your leader (please)" )
);

thirdTransaction.commit();
thirdSession.close();

// ############################################################################

// Final unit of work (just repeat the query)
// TODO: You can move this query into the thirdSession before the commit, makes more sense!
Session fourthSession = HibernateUtil.getSessionFactory().openSession();
Transaction fourthTransaction = fourthSession.beginTransaction();

messages =
fourthSession.createQuery("from Message m order by m.text asc").list();

System.out.println( messages.size() + " message(s) found:" );

for ( Iterator iter = messages.iterator(); iter.hasNext(); ) {
Message loadedMsg = (Message) iter.next();
System.out.println( loadedMsg.getText() );
}

fourthTransaction.commit();
fourthSession.close();


// Shutting down the application
HibernateUtil.shutdown();
}
}


Top
 Profile  
 
 Post subject:
PostPosted: Sat Apr 28, 2007 11:19 am 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
Did you compare it to the downloadable source code, which runs?

_________________
JAVA PERSISTENCE WITH HIBERNATE
http://jpwh.org
Get the book, training, and consulting for your Hibernate team.


Top
 Profile  
 
 Post subject:
PostPosted: Sat Apr 28, 2007 2:32 pm 
Newbie

Joined: Thu Apr 19, 2007 8:55 pm
Posts: 4
I've run the code in the helloworld-jpa directory of the jpwh-gettingstarted-070401.zip download file. It does work. But I would like to understand, and run, the example code that is given in "Java Persistance with Hibernate" in section 2.2.1 on pages 68 through 71. I'd like to understand Hibernate thoroughly, and to understand how to use the changes such as using "AnnotationConfiguration" class in the HibernateUtil class, and the "<mapping class="hello.Message"/> element in the hibernate.cfg.xml file.
The example in the helloworld-jpa directory uses an entity manager, and I can't find code to download for the section 2.2.1 example. I'd like to understand everything in the book as I read along. Am I not finding the correct download? Have I entered incorrectly or misunderstood the changes discussed on pages 68 through 71? It seems that what is being said is that the code from the very first helloworld native example is modified as discussed on pages 68 to 71, and then the modified example will run. I'd like to understand what is missing, and how to correctly use the methods describes in this section before I go onto the EntityManager use.


Top
 Profile  
 
 Post subject:
PostPosted: Sat Apr 28, 2007 4:47 pm 
Newbie

Joined: Thu Apr 19, 2007 8:55 pm
Posts: 4
I solved the problem.

I used the following lines in the HibernateUtil class:

.
.
static {
try {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass(hello.Message.class);
cfg.configure("hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
} catch
.
.


In the original code, the problem was that the ExceptionInInitializerError was thrown, because the file that defined the JDBC and dialect properties was not being found in the block where the SessionFactory was created.


Top
 Profile  
 
 Post subject:
PostPosted: Thu May 10, 2007 11:39 am 
Newbie

Joined: Thu May 10, 2007 10:25 am
Posts: 1
Location: Toronto
Actually loading the sessionFactory this this way though correct isn't terribly effecient either, if used exactly as typed

static {
try {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg.addAnnotatedClass(hello.Message.class);
cfg.configure("hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
} catch
.

try ...

static {
try {
sessionFactory = new AnnotationConfiguration()
.configure("/hibernate.cfg.xml")
.buildSessionFactory();
} catch
.

assuming your hibernate.cfg.xml file maps the Message POJO as a resource
<mapping resource="hello/Message.hbm.xml"/>


Top
 Profile  
 
 Post subject:
PostPosted: Sat May 12, 2007 3:05 am 
Newbie

Joined: Thu May 10, 2007 6:19 am
Posts: 1
cingram007 - I'm not sure why you would want to use a mapping document with JPA since JPA uses annotations in the Message class.


Top
 Profile  
 
 Post subject:
PostPosted: Sat May 12, 2007 9:16 am 
Newbie

Joined: Thu Apr 19, 2007 8:55 pm
Posts: 4
_Andrew_'s statement above reflects the way this hello world example was written. Since the example uses annotations, the hibernate.cfg.xml file uses the following line:

<mapping class ="hello.Message"/>

My first post, above, lists the hibernate.cfg.xml file used in this example.

If the helloworld example had used Hibernate native, then the following line would have been used in the hibernate.cfg.xml file:

<mapping resource ="hello/Message.hbm.xml"/>

My original post was about annotations.


cingram007's post gives an example of command chaining, which can be used because each of the methods returns an object:

addAnnotatedClass(hello.Message.class) returns an AnnotationConfiguration object

configure("hibernate.cfg.xml") returns a Configuration object

buildSessionFactory() returns a Configuration object

This java programming tool wasn't really relevant to the example


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.