Hibernate SessionFactory in a cluster?
I have been developing an application on WLS 8.1.4 with hibernate 3.1.2 .
On WLS I created
- adminServer on localhost:7001
- MyCluster group
- manageServer1 on localhost:7021
- manageServer2 on localhost:7022
I deploy TestEjb.ejb on MyCluster
TestEjb.ejb
- META-INF
- ejbModule.jar
- hibernate3.jar and lib for hibernate
* Hibernate 3.1.2 doesn't have problem about ANTLR.
hibernate.cfg.xml
<property name="session_factory_name">sessionFactory</property>
<property name="hibernate.jndi.class">weblogic.jndi.WLInitialContextFactory</property>
<property name="hibernate.jndi.url">t3://localhost:7021</property>
<property name="transaction.factory_class">org.hibernate.transaction.CMTTransactionFactory</property>
<property name="hibernate.transaction.manager_lookup_class">org.hibernate.transaction.WeblogicTransactionManagerLookup</property>
SessionBean
public class TestServiceBeanImpl
extends TestServiceBean
implements SessionBean
public java.lang.Boolean testMethod() {
try {
new Configuration().configure().buildSessionFactory();
} catch (Exception ex) {
log.error("error", ex);
throw new RuntimeException(ex);
return null;
public java.lang.Boolean testMethod2() {
try {
InitialContext ct = new InitialContext();
Object obj = ct.lookup("sessionFactory");
log.info("obj : " + obj);
} catch (Exception ex) {
ex.printStackTrace();
throw new EJBException(ex);
return null;
Test client
public class TestServiceTestClient2 {
private TestServiceRemote testServiceRemote = null;
private TestServiceRemoteHome testServiceRemoteHome = null;
//Construct the EJB test client
public TestServiceTestClient2() {
initialize();
try {
testServiceRemote = testServiceRemoteHome.create();
testServiceRemote.testMethod();
} catch (Exception ex) {
ex.printStackTrace();
public void initialize() {
try {
//get naming context
Context context = getInitialContext();
//look up jndi name
Object ref = context.lookup("TestService");
//look up jndi name and cast to Home interface
testServiceRemoteHome = (TestServiceRemoteHome)
PortableRemoteObject.narrow(ref,
TestServiceRemoteHome.class);
} catch (Exception e) {
e.printStackTrace();
public Context getInitialContext() throws Exception {
String url = "t3://127.0.0.1:7021";
Properties properties;
try {
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
properties.put(Context.PROVIDER_URL, url);
return new javax.naming.InitialContext(properties);
} catch (Exception e) {
throw e;
public static void main(String[] args) {
TestServiceTestClient2 client = new TestServiceTestClient2();
I'm not sure about property "hibernate.jndi.url". Is it right?
I create test client to invoke TestServiceBean method testMethod() on localhost:7021 that work I can binding "sessionFactory" on manageServer1 and manageServer2 (I use WLS console view JNDI tree on manageServer1 and manageServer2) and I invoke testMethod2() on localhost:7021, I can lookup SessionFactory object from JNDI.
Then I change test client to invoke testMethod2() on localhost:7022, I get null from JNDI.
This is warning on my console
13 3 2006 18:42:21,968 WARN org.hibernate.impl.SessionFactoryObjectFactory - Not found: 2c9498dc09f356340109f36711790001
13 3 2006 18:42:21,968 INFO test.service.TestService_8oegc0_Impl - obj : null
How can i solve the problem?
Thanks in advance for tips or other suggestions!
Regards,
piya
ANTLR classloading ?
http://www.hibernate.org/250.html#A25
Similar Messages
-
Hibernate SessionFactory: best practice
Hi all,
Can someone please suggest on the best practice for using Hibernate SessionFactory? Meaning, initializing the SessionFactory object in the most optimzed manner which can be used across the application in a very convenient manner.
Please help.837173 wrote:
Hi all,
Can someone please suggest on the best practice for using Hibernate SessionFactory? Meaning, initializing the SessionFactory object in the most optimzed manner which can be used across the application in a very convenient manner.
Please help.If there is such a thing as a most optimized manner, why would the less-optimized possibilities even exist eh? Its so easy to reason if something makes sense or not, please try to do so the next time you have a question. -
Can we bind hibernate sessionFactory to weblogic JNDI from remote client?
Hi,
Is it possible to bind a hibernate sessionfactory from a remote jee client application to weblogic 10.3 server ?
Thanks
ow005480Hi Michael,
Please make sure that your Mail Session "mail/MYAPP_MAIL" is targeted to the same Server where you are trying to deploy your Spring based application. It means in the JNDi tree of the Server do you see the JNDI name "mail/MYAPP_MAIL" where you are trying to deploy your application?
You can check the JNDI tree of your server using AdminConsole after login please nevigate to the following :
AdminConsole---->Servers ----[SERVER_NAME] click ----> (View jndi tree) link
Thanks
Jay SenSharma
http://middlewaremagic.com/weblogic/ (Middleware Magic Is Here) -
Using a pre-configured Hibernate SessionFactory
Is it possible for the HibernateCacheLoader/HibernateCacheStore to use a pre-configured SessionFactory? We use Hibernate's annotation based configuration and use Spring to build our SessionFactory for us.
It seems that the Coherence HibernateCacheLoader/HibernateCacheStore is hard wired to build the configuration from scratch.
ThanksHello,
With the current release of the product you are correct it is not possible.
This issue has been scheduled to be fixed in the next release of the product.
We hope to have that release out soon but we can not give any specific time lines of the release.
I hope this answers your questions.
-Dave -
Servlet inserting record into postgresql through hibernate
Hi
I have developed a servlet. This servlet is inserting record into postgres sql through hibernate using eclispe ide. When I run my code then I find the following exception
exception
java.lang.NullPointerException
hibernate.example.FirstExample.doGet(FirstExample.java:54)
javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
I have developed the following code
package hibernate.example;
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
public String getEmail() {
return email;
public String getFirstName() {
return firstName;
public String getLastName() {
return lastName;
public void setEmail(String string) {
email = string;
public void setFirstName(String string) {
firstName = string;
public void setLastName(String string) {
lastName = string;
public long getId() {
return id;
public void setId(long l) {
id = l;
**Now the servlet is**
package hibernate.example;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class FirstExample extends HttpServlet {
Session session = null;
public String getServletInfo() {
return "Servlet connects to PostgreSQL database and displays result of a SELECT";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Configuration cfg = new Configuration().configure();
SessionFactory factory = cfg.buildSessionFactory();
session = factory.openSession();
out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Deepak");
contact.setLastName("Kumar");
contact.setEmail("[email protected]");
session.save(contact);
out.println("Done");
catch(Exception e){
System.err.println(e.getMessage());
finally{
session.flush();
session.close();
**web.xml is**
<web-app>
<database>
<driver>
<type>org.postgresql.Driver</type>
<url>jdbc:postgresql://127.0.0.1:5432/ali</url>
<user>ali</user>
<password>ali</password>
</driver>
</database>
<servlet>
<servlet-name>FirstExample</servlet-name>
<servlet-class>hibernate.example.FirstExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstExample</servlet-name>
<url-pattern>/hb</url-pattern>
</servlet-mapping>
</web-app>
**And contact.hbm.xml is**
<?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="hibernate.example.Contact" table="CONTACT">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
</hibernate-mapping>
**And hibernate.cfg.xml is**
<?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">com.postgressql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://127.0.0.1:5432/ali</property>
<property name="hibernate.connection.username">ali</property>
<property name="hibernate.connection.password">ali</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Pleas tell me that where I have done the mistake and how can I resolove the error.ahmadgee wrote:
Thank u very much.
First I tried with out the servlet. I took a simple class. But it was displaying the null pointer exception.
then you still have the problem. do you understand the root cause?
After then I made a servlet. how was that going to help your null pointer exception?
Now it is displaying error hibernate.cfg.xml not found.that's part of the problem. where is the servlet reading that file and initializing the session factory? how is it finding that file?
i don't know where you have that .cfg.xml file, or where the recommended place is where hibernate expects to see it, but i'd bet it needs to be in the CLASSPATH, which means WEB-INF/classes.
figure out why you get that NPE first, though. the servlet is only making things worse.
% -
Mapping Problem using hibernate and annotations
Hi,
i am German student and new to hibernate. I established a mn conetction between to entities using hbm.xml mapping files. now I try to create the same connection applying annotations. unfortunately it does not work and I do not now why. First my error message followed by my classes and xml's:
Initial SessionFactory creation failed.org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: domain.Termin.person in domain.Person.termine
Exception in thread "main" java.lang.ExceptionInInitializerError
at services.HibernateUtil.sessionFactory(HibernateUtil.java:39)
at services.HibernateUtil.getSessionFactory(HibernateUtil.java:20)
at test.Test.main(Test.java:20)
Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: domain.Termin.person in domain.Person.termine
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:552)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:517)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1130)
at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:316)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:915)
at services.HibernateUtil.sessionFactory(HibernateUtil.java:36)
... 2 more
package domain;
import java.util.LinkedList;
import java.util.List;
import domain.Termin;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "PERSON")
public class Person {
private long id;
private String vorname;
private String nachname;
private List<Termin> termine=new LinkedList<Termin>();
public Person() {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public long getId() {
return id;
public void setId(long id) {
this.id = id;
public String getNachname() {
return nachname;
public void setNachname(String nachname) {
this.nachname = nachname;
public String getVorname() {
return vorname;
public void setVorname(String vorname) {
this.vorname = vorname;
public void addTermin(Termin termin){
termine.add(termin);
@ManyToMany(mappedBy="person")
public List<Termin> getTermine() {
return termine;
public void setTermine(List<Termin> termine) {
this.termine = termine;
package domain;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name = "TERMIN")
public class Termin {
private long id;
private String titel;
private Person eigentuemer;
private List<Person> teilnehmer= new ArrayList<Person>();
public void addTeilnehmer(Person person){
teilnehmer.add(person);
@ManyToMany
public List<Person> getTeilnehmer() {
return teilnehmer;
public void setTeilnehmer(List<Person> teilnehmer) {
this.teilnehmer = teilnehmer;
public Termin() {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public long getId() {
return id;
public void setId(long id) {
this.id = id;
public String getTitel() {
return titel;
public void setTitel(String titel) {
this.titel = titel;
public Person getEigentuemer() {
return eigentuemer;
public void setEigentuemer(Person eigentuemer) {
this.eigentuemer = eigentuemer;
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import services.HibernateUtil;
import domain.Person;
import domain.Termin;
public class Test {
public static void main(String[] args) {
Session session = null;
HibernateUtil.setRecreateDB(true);
session = HibernateUtil.getSessionFactory().getCurrentSession();
/* Person person1 =new Person();
person1.setNachname("P1");
Transaction transaction = session.beginTransaction();
session.save(person1);
transaction.commit();
Person person2 =new Person();
person2.setNachname("P2");
session = HibernateUtil.getSessionFactory().getCurrentSession();
transaction = session.beginTransaction();
session.save(person2);
transaction.commit();
Termin termin1 =new Termin();
termin1.setTitel("T1");
termin1.setEigentuemer(person1);
termin1.addTeilnehmer(person1);
termin1.addTeilnehmer(person2);
session = HibernateUtil.getSessionFactory().getCurrentSession();
transaction = session.beginTransaction();
session.save(termin1);
transaction.commit();
Termin termin2 =new Termin();
termin2.setTitel("t2");
termin2.setEigentuemer(person1);
termin2.addTeilnehmer(person1);
termin2.addTeilnehmer(person2);
transaction = session.beginTransaction();
session.save(termin2);
transaction.commit();
session.close();
package services;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import domain.Person;
import domain.Termin;
public class HibernateUtil {
private static boolean recreateDB = false;
public static void setRecreateDB(boolean recreateDB) {
HibernateUtil.recreateDB = recreateDB;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = sessionFactory("hibernate.cfg.xml");
return sessionFactory;
private static SessionFactory sessionFactory = null;
private static SessionFactory sessionFactory(String configurationFileName) {
try {
AnnotationConfiguration annotationConfiguration =
new AnnotationConfiguration()
.addAnnotatedClass(Person.class)
.addAnnotatedClass(Termin.class);
if (recreateDB) annotationConfiguration.setProperty("hibernate.hbm2ddl.auto", "create");
annotationConfiguration.configure();
return annotationConfiguration.buildSessionFactory();
} catch (Throwable ex){
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
<?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.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.password">application</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">application</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>The error message is pretty much telling you the problem:
mappedBy reference an unknown target entity property: domain.Termin.person in domain.Person.termine
This tells you that there's a mappedBy setting on the Person class's termine property annotation, and that the property it's referring to (the person property of the Termin class) doesn't exist.
@ManyToMany(mappedBy="person")
public List<Termin> getTermine() {
return termine;
}If we have a look at the Termin class, indeed it has the following properties:
id
teilnehmer
titel
eigentuemerAnd no person property. Remember, a property is defined by the existence of a get/set pair for the name. It's unrelated to the types returned by them and the private variables implementing them.
mappedBy has the equivalent effect to the inverse property in a hbm.xml mapping file - it defines which entity's property will cause the foreign key value to be updated (persisting the relationship to the database). From the context of your code, I'm guessing you really want the annotation to read:
@ManyToMany(mappedBy="teilnehmer") -
How to configure Sesion Factory in Hibernate to implement getCurrentSession
Hi,
I am new in Hibernate and I am using an application where I need to improve the performance while uploading the users through a utility. While analyzing the system, I found that, to insert a single user there were around 8 hits are made to DB to get the information and based on that finally it inserts the user. The strange thing I have noticed is that for every hit, a new DB connection is opened in code using the snippet getHibernateTemplate().getSessionFactory().openSession();
However, the connection is getting closed in finally block. But I think instead of using Open Connection; getCurrentSession can save time.
Can any one suggest whether I am on right track?
Also, when I have tried to use getCurrentSession I have simply replaced "getHibernateTemplate().getSessionFactory().openSession();" with "getHibernateTemplate().getSessionFactory().getCurrentSession();" from everywhere in code.
But when I tried to run the Utility I got some Hibernate Exception stating "No Hibernate Session bound to thread, and configuration does not allow creation".
Could anyone suggest do I need to configure anything else in my applicationcontext.xml to use the getCurrentSession() method.
Thanks in advance.the method getCurrentSession() should be done using Singleton factory method so that you have only one connection per application. You can implement something like this as coded below:
import java.io.File;
import javax.naming.InitialContext;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
* @author hennebrueder This class garanties that only one single SessionFactory
* is instanciated and that the configuration is done thread safe as
* singleton. Actually it only wraps the Hibernate SessionFactory.
* When a JNDI name is configured the session is bound to to JNDI,
* else it is only saved locally.
* You are free to use any kind of JTA or Thread transactionFactories.
public class InitSessionFactory {
* Default constructor.
private InitSessionFactory() {
* Location of hibernate.cfg.xml file. NOTICE: Location should be on the
* classpath as Hibernate uses #resourceAsStream style lookup for its
* configuration file. That is place the config file in a Java package - the
* default location is the default Java package.<br>
* <br>
* Examples: <br>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
private static String CONFIG_FILE_LOCATION = "<Path to hibernate.cfg.xml>";
/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();
/** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory;
* initialises the configuration if not yet done and returns the current
* instance
* @return
public static SessionFactory getInstance() {
if (sessionFactory == null)
initSessionFactory();
return sessionFactory;
* Returns the ThreadLocal Session instance. Lazy initialize the
* <code>SessionFactory</code> if needed.
* @return Session
* @throws HibernateException
public Session openSession() {
return sessionFactory.getCurrentSession();
* The behaviour of this method depends on the session context you have
* configured. This factory is intended to be used with a hibernate.cfg.xml
* including the following property <property
* name="current_session_context_class">thread</property> This would return
* the current open session or if this does not exist, will create a new
* session
* @return
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
* initializes the sessionfactory in a safe way even if more than one thread
* tries to build a sessionFactory
private static synchronized void initSessionFactory() {
* [laliluna] check again for null because sessionFactory may have been
* initialized between the last check and now
Logger log = Logger.getLogger(InitSessionFactory.class);
if (sessionFactory == null) {
try {
File f = new File(CONFIG_FILE_LOCATION);
cfg.configure(f);
String sessionFactoryJndiName = cfg
.getProperty(Environment.SESSION_FACTORY_NAME);
if (sessionFactoryJndiName != null) {
cfg.buildSessionFactory();
log.debug("get a jndi session factory");
sessionFactory = (SessionFactory) (new InitialContext())
.lookup(sessionFactoryJndiName);
//sessionFactory = new AnnotationConfiguration().configure(System.getProperty("user.dir") + "\\" + CONFIG_FILE_LOCATION).buildSessionFactory();
} else{
log.debug("classic factory");
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating HibernateSessionFactory %%%%");
e.printStackTrace();
throw new HibernateException(
"Could not initialize the Hibernate configuration");
public static void close(){
if (sessionFactory != null)
sessionFactory.close();
sessionFactory = null;
}Test it and let me know. -
Using Hibernate on OC4J 10.1.3
How can I use hibernate in my application server, anyone has a reference?
Thanks.There's an easy way if you don't need hibernate to be working behind the scene (e.g, replacing TopLink as the JPA implementation).
Basically, you just need to initialize hibernate SessionFactory once on startup, and put it somewhere accessible from your business logic code.
On servlet container, usually you would want to attach a ContextLoaderListener and initialize hibernate there and put it in ServletContext. You can then get sessionFactory from your servlets using httpServletRequest.getSession().getServletContext().
Same idea for ejb. I'm not sure how to accomplish that though. Maybe instantiating the sessionFactory in a startup listener and register it on JNDI. I'm not sure, still learning all these EJB stuff.
Rudi -
Org.hibernate.MappingException: invalid configuration in hibernate
hi,
i am new to hibernate.
while i am executing small program, below error occur.
what can i do to solve this problem, plz help me.
Error Code
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception occur:invalid configuration
org.hibernate.MappingException: invalid configuration+
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1493)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1434)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1420)
at FirstExample.main(FirstExample.java:12)
Caused by: org.xml.sax.SAXParseException: Document is invalid: no grammar found.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1490)
... 3 more
Exception in thread "main" java.lang.NullPointerException
at FirstExample.main(FirstExample.java:26)Thank u .
I did all configuration properly by some guideline.
But i got new error in my program.
please reply me.
This is my program
*{color:#3366ff}Test.java{color}*
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import event.Sample;
public class Test {
public static void main(String a[])throws HibernateException
Session session=null;
try
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
session=sessionFactory.openSession();
System.out.println("Insert record ");
Sample s=new Sample();
s.setId(3);
s.setName("Sundar");
session.save(s);
System.out.println("Sucessfully Saved");
}catch(Exception e)
System.out.println("Exception occur:"+e.getMessage());
e.printStackTrace();
}finally
session.flush();
session.close();
*{color:#3366ff}Java Bean Sample.java{color}*
package event;
public class Sample {
private int id;
private String name;
public int getId() {
return id;
public void setId(int id) {
this.id = id;
public String getName() {
return name;
public void setName(String name) {
this.name = name;
*{color:#3366ff}{color:#ff0000}hibernate.cfg.xml file{color}*
*<?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>*
* <!-- local connection properties -->*
* <property name="hibernate.connection.url">*
* jdbc:mysql://localhost:3306/test*
* </property>*
* <property name="hibernate.connection.driver_class">*
* com.mysql.jdbc.Driver*
* </property>*
* <property name="hibernate.connection.username">root</property>*
* <property name="hibernate.connection.password">server</property>*
* <!-- property name="hibernate.connection.pool_size"></property -->*
* <!-- dialect for MySQL -->*
* <property name="dialect">*
* org.hibernate.dialect.MySQLDialect*
* </property>*
* <property name="hibernate.show_sql">false</property>*
* <property name="hibernate.transaction.factory_class">*
* org.hibernate.transaction.JDBCTransactionFactory*
* </property>*
* <mapping resource="event/Sample.hbm.xml" />*
* </session-factory>*
*</hibernate-configuration>*
*{color:#ff0000}{color:#000000}Sample.hbm.xml file{color}*
*<?xml version="1.0" encoding="utf-8"?>*
*<!DOCTYPE hibernate-mapping PUBLIC*
* "-//Hibernate/Hibernate Mapping DTD//EN"*
* "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >*
*<hibernate-mapping package="event">*
* <class name="Sample" table="sample" >*
* <meta attribute="sync-DAO">true</meta>*
* <property name="Id" column="id" type="integer" not-null="false" length="11" />*
* <property name="Name" column="name" type="string" not-null="false" length="50" />*
* </class>*
*</hibernate-mapping>*
*{color}{color}*
*{color:#3366ff}
This is my error.{color}*
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception occur:Could not parse mapping document from resource event/Sample.hbm.xml
org.hibernate.InvalidMappingException: Could not parse mapping document from resource event/Sample.hbm.xml
at org.hibernate.cfg.Configuration.addResource(Configuration.java:575)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1593)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1561)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1540)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1514)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1434)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1420)
at Test.main(Test.java:15)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:508)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:572)
... 7 more
Caused by: org.xml.sax.SAXParseException: The content of element type "class" must match "(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,resultset*,(query|sql-query)*)".
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleEndElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.endElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanEndElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:505)
... 8 more
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:29) -
Many-to-one relationship using annotations in hibernates...
my pojo class is M_Product_Category
package com.netree.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.OneToMany;
import javax.persistence.JoinColumn;
@Entity
@Table(name="m_product_category")
public class M_Product_Category implements Serializable{
@Id
@Column(name="MPC_ID")
@GeneratedValue
private int mpc_Id;
@Column(name="IsActive")
private int isActive;
@Column(name="Category_Name")
private String category_Name;
@Column(name="Category_Description")
private String category_Description;
@Column(name="Parent_MPC_ID")
private int parent_MPC_ID;
public M_Product_Category(){
public M_Product_Category(int mpc_Id, int isActive, String category_Name,
String category_Description, int parent_MPC_ID) {
super();
this.mpc_Id = mpc_Id;
this.isActive = isActive;
this.category_Name = category_Name;
this.category_Description = category_Description;
this.parent_MPC_ID = parent_MPC_ID;
public int getMpc_Id() {
return mpc_Id;
public void setMpc_Id(int mpc_Id) {
this.mpc_Id = mpc_Id;
public int getIsActive() {
return isActive;
public void setIsActive(int isActive) {
this.isActive = isActive;
public String getCategory_Name() {
return category_Name;
public void setCategory_Name(String category_Name) {
this.category_Name = category_Name;
public String getCategory_Description() {
return category_Description;
public void setCategory_Description(String category_Description) {
this.category_Description = category_Description;
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="Parent_MPC_ID", referencedColumnName="MPC_ID")
public int getParent_MPC_ID() {
return parent_MPC_ID;
public void setParent_MPC_ID(int parent_MPC_ID) {
this.parent_MPC_ID = parent_MPC_ID;
This is anothe pojo class i.e., ProductMaster:
package com.netree.model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "M_Product_Master")
public class ProductMaster implements Serializable {
@Id
@GeneratedValue
@Column(name = "MPM_ID")
private int mpmID;
@Column(name = "Product_Name")
private String productName;
@Column(name = "Product_Description")
private String productDescription;
@Column(name = "Standard_Cost")
private String price;
@Column(name = "Image_URL_Big")
private String image;
@Column(name = "MPC_ID")
private int mpc_id;
public int getMpc_id() {
return mpc_id;
public void setMpc_id(int mpc_id) {
this.mpc_id = mpc_id;
private M_Product_Category product_Category;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "mpc_id", referencedColumnName = "MPC_ID")
public M_Product_Category getProduct_Category() {
return product_Category;
public void setProduct_Category(M_Product_Category product_Category) {
this.product_Category = product_Category;
public int getMpmID() {
return mpmID;
public void setMpmID(int mpmID) {
this.mpmID = mpmID;
public String getProductName() {
return productName;
public void setProductName(String productName) {
this.productName = productName;
public String getProductDescription() {
return productDescription;
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
public String getPrice() {
return price;
public void setPrice(String price) {
this.price = price;
public String getImage() {
return image;
public void setImage(String image) {
this.image = image;
util class...
package com.netree.Util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
public static SessionFactory getSessionFactory() {
System.out.println("sessionFactory");
AnnotationConfiguration annotationConfiguration = new AnnotationConfiguration();
System.out.println("annotationConfiguration");
annotationConfiguration=annotationConfiguration.configure("com/netree/Cfg/Hibernate.cfg.xml");
SessionFactory sessionFactory = annotationConfiguration.buildSessionFactory();
return sessionFactory;
package com.netree.DaoImpl;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import com.netree.Util.HibernateUtil;
import com.netree.model.ProductMaster;
public class ProductMasterImpl {
public static void main(String args[]) {
try{
System.out.println("sessionFactory starts");
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
System.out.println("sessionFactory ends");
Session session=sessionFactory.getCurrentSession();
Transaction transaction=session.beginTransaction();
Criteria ctr=session.createCriteria(ProductMaster.class).add(Restrictions.eq("mpc_id",new Integer(39)));
List<ProductMaster> list=ctr.list();
@SuppressWarnings("rawtypes")
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
ProductMaster productMaster = (ProductMaster) iterator.next();
System.out.println(productMaster.getMpmID());
System.out.println(productMaster.getProductName());
System.out.println(productMaster.getProductDescription());
System.out.println(productMaster.getPrice());
System.out.println(productMaster.getImage());
System.out.println(productMaster.getProduct_Category().getMpc_Id());
System.out.println(productMaster.getProduct_Category().getCategoryName());
System.out.println(productMaster.getProduct_Category().getCategory_Description());
session.close();
catch(Exception ex){
System.out.println(ex.getMessage());
finally{
Already i have two tables in database with the suitable records... I want to retrieve the data by using MPC_ID from both tables....
when i run this program i am getting query but it is showing exception i.e....
Hibernate: select this_.MPM_ID as MPM1_1_0_, this_.Image_URL_Big as Image2_1_0_, this_.MPC_ID as MPC3_1_0_, this_.Standard_Cost as Standard4_1_0_, this_.Product_Description as Product5_1_0_, this_.Product_Name as Product6_1_0_, this_.product_Category as product7_1_0_ from M_Product_Master this_ where this_.MPC_ID=?
could not execute query
could u pls help me in this regard.....in the cube do you have both of these values
PT02 211886
PT02 211887
or its always either one of them. I dont think changing your cube design would prove any helpful in this scenario. I believe its more of a data issue than the design issue. You would need to change the way the data is entered into the cube with the different measurement assigned to the unit.
on a second thought(I understand that you dont have a luxury to change the cube design), when you say you can see diff measurement type assigned to one unit in the masterdata, you can make the unit attribute as a navigational attribute in both the IO and cube. And just map measurent type in the update rules and derive the units from the masterdata table in the report.... does it make sense?
Message was edited by:
voodi -
SUN AppServer PE 8.2 with Hibernate security problems
All,
I have an EAR (EJB + WEB) successfully deployed and working on JBoss 4.0.3SP1, IBM WebSphere, BEA Weblogic. I am currently trying to deploy it on SUN AppServer PE 8.2 and am running into lots of security issues.
So far I had to add the following to my /home/sandeepk/apps/SUNWappserver/domains/domain1/config/server.policy file:
grant {
// Permission for allowing Hibernate read/write from it's configuration files.
permission java.util.PropertyPermission "*", "read,write";
// Permission for cglib part of Hibernate framework
permission java.lang.RuntimePermission "getProtectionDomain";
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
// Permissions to get Apache Axis to work
permission java.lang.RuntimePermission "createClassLoader";
permission java.lang.RuntimePermission "getClassLoader";
grant codeBase "file:${com.sun.aas.installRoot}/domains/domain1/applications/j2ee-modules/-" {
permission java.security.AllPermission;
The above additions resolved Apache Axis and Hibernate SessionFactory security issues but I still get the following Exception which I am not able to figure out how to resolve.
javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:2807)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:2713)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:2521)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:819)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:160)
at $Proxy174.findHelpScreenObjectsNoGuid(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(Unknown Source)
at com.sun.corba.ee.impl.presentation.rmi.bcel.BCELStubBase.invoke(Unknown Source)
at com.adminserver.dal._HelpScreenFacadeRemote_DynamicStub.findHelpScreenObjectsNoGuid(_HelpScreenFacadeRemote_DynamicStub.java)
at com.adminserver.utl.HibernateInitUtl.init(HibernateInitUtl.java:43)
at javax.servlet.GenericServlet.init(GenericServlet.java:261)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:118)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1093)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:931)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4183)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4536)
at com.sun.enterprise.web.WebModule.start(WebModule.java:241)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1086)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:847)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1086)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:483)
at org.apache.catalina.startup.Embedded.start(Embedded.java:894)
at com.sun.enterprise.web.WebContainer.start(WebContainer.java:741)
at com.sun.enterprise.web.PEWebContainer.startInstance(PEWebContainer.java:515)
at com.sun.enterprise.web.PEWebContainerLifecycle.onStartup(PEWebContainerLifecycle.java:54)
at com.sun.enterprise.server.ApplicationServer.onStartup(ApplicationServer.java:300)
at com.sun.enterprise.server.PEMain.run(PEMain.java:294)
at com.sun.enterprise.server.PEMain.main(PEMain.java:220)
Caused by: java.lang.IllegalStateException: Operation not allowed
at com.sun.ejb.containers.PMTransactionManagerImpl.suspend(PMTransactionManagerImpl.java:91)
at org.hibernate.cache.TreeCache.suspend(TreeCache.java:101)
at org.hibernate.cache.TreeCache.put(TreeCache.java:71)
at org.hibernate.cache.TransactionalCache.put(TransactionalCache.java:50)
at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:126)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:530)
at org.hibernate.loader.Loader.doQuery(Loader.java:436)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:218)
at org.hibernate.loader.Loader.doList(Loader.java:1593)
at org.hibernate.loader.Loader.list(Loader.java:1577)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:395)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:271)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:844)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:74)
at com.adminserver.dal.HelpScreenFacadeEJB.findHelpScreenObjectsNoGuid(HelpScreenFacadeEJB.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at com.sun.enterprise.security.SecurityUtil$2.run(SecurityUtil.java:153)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.enterprise.security.application.EJBSecurityManager.doAsPrivileged(EJBSecurityManager.java:957)
at com.sun.enterprise.security.SecurityUtil.invoke(SecurityUtil.java:158)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:151)
... 36 more
Any ideas?
--Sandeep KhannaMy guess is that the hibernate code is assuming there's a fully-functional transaction manager available at "java:pm/TransactionManager". The J2EE SDK codebase has an internal TM available there but it doesn't support all TM operations, which is why it throws an exception during suspend(). The spec doesn't require that anything be available at java:pm/TransactionManager. There was a requirement for it in an early version of the EJB 2.0 spec but it was removed along with the other container/persistence-manager pluggability contracts in the final release of EJB 2.0.
-
ApplicationContext-hibernate.xml con't load
My configuration is Spring2.5 netbeans6.0 Tomcat6.0.14 not having any single jar
when i start my application it gives an error that applicationContext-hibernate.xml
<code>
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [WEB-INF/applicationContext_1.xml]: Invocation of init method failed; nested exception is org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1362)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:540)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:485)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:169)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:170)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:407)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:735)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:369)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:251)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:190)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3830)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4337)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from invalid mapping
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:502)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:595)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1390)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1359)
... 38 more
Caused by: org.xml.sax.SAXParseException: The content of element type "class" must match "(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,resultset*,(query|sql-query)*)".
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.handleEndElement(Unknown Source)
at org.apache.xerces.impl.dtd.XMLDTDValidator.endElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.dom4j.io.SAXReader.read(SAXReader.java:465)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:499)
</code>
my applicationContext-hibernate.xml file is here
<code>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<!--
- Application context definition for RoseIndia Login Application on Hibernate.
-->
<beans>
<!-- ========================= RESOURCE DEFINITIONS ========================= -->
<!-- Configurer that replaces ${...} placeholders with values from a properties file -->
<!-- (in this case, JDBC-related settings for the dataSource definition below) -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>/WEB-INF/jdbc.properties</value></property>
</bean>
<!-- Local DataSource that works in any environment -->
<!-- Note that DriverManagerDataSource does not pool; it is not intended for production -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
<property name="url"><value>${jdbc.url}</value></property>
<property name="username"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
<!-- JNDI DataSource for J2EE environments -->
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref local="dataSource"/></property>
<property name="mappingResources">
<list>
<value>roseindia/dao/hibernate/Login.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
<!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->
<!--
Data access object: Hibernate implementation.
-->
<bean id="HibernateSpringDaoTarget" class="roseindia.dao.SpringHibernateDAOImpl">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
<!--
- Transactional proxy for Login Application central data access object.
- Defines specific transaction attributes with "readOnly" markers,
- which is an optimization that is particularly valuable with Hibernate
- (to suppress unnecessary flush attempts for read-only operations).
- Note that in a real-life app with multiple transaction proxies,
- you will probably want to use parent and child bean definitions
- as described in the manual, to reduce duplication.
-->
<bean id="SpringHibernateDao" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"><ref local="transactionManager"/></property>
<property name="target"><ref local="HibernateSpringDaoTarget"/></property>
<property name="transactionAttributes">
<props>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="store*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<!-- Email Service-->
<bean id="mailbean" class="roseindia.web.common.SendMail">
<property name="strSmtp"><value>mail.waproductsuite.com</value></property>
</bean>
</beans>
</code>DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
String jdbcURL="jdbc:oracle:thin:@"
+"192.168.0.96"//jdbcHost
+":1521"//port
+":db12"//service name
//Another format: DriverManager.getConnection("jdbc:oracle:oci8:@","user", "passwd");
should work normally. If not, try to download a JDBC packag from Oracle site. -
Hi,
how you guys select multiple rows from mysql database via hibernate?
I could select but I only able to get one row out of multiple rows.
int id = 1;
Query query = HibernateUtil.getSession().createQuery("select u from UcoopThread u where u.id = :id");
query.setInteger("id", id);
Collection<UcoopThread> q = (Collection<UcoopThread>) query.list();The above select query should give me several rows but if I pint the collection content then I will only get one row.
I have also tried query.uniqueResult() , and I get the same result, any help?
Thanks for consideration.Because I'm a nice guy, here's an example (and my last shot at breaking through the fog):
Category:package yawmark.hibernate.demo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "category")
public class Category {
private int id;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getId() {
return id;
public void setId(int id) {
this.id = id;
UcoopThread:package yawmark.hibernate.demo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "thread")
public class UcoopThread {
private int tid;
private String threadName;
private Category category;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public int getTid() {
return tid;
public void setTid(int id) {
tid = id;
public String getThreadName() {
return threadName;
public void setThreadName(String threadName) {
this.threadName = threadName;
@ManyToOne
@JoinColumn(name = "category_id")
public Category getCategory() {
return category;
public void setCategory(Category category) {
this.category = category;
@Override
public String toString() {
return "[" + threadName + ":" + category.getId() + "]";
Main:package yawmark.hibernate.demo;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.springframework.orm.hibernate3.HibernateTemplate;
public final class Main {
public static void main(String[] args) {
Configuration cfg = new AnnotationConfiguration()
.setProperty("hibernate.connection.driver_class", "org.hsqldb.jdbcDriver")
.setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:demo")
.setProperty("hibernate.connection.username", "sa")
.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect")
.setProperty("hibernate.hbm2ddl.auto", "create-drop")
.addAnnotatedClass(UcoopThread.class)
.addAnnotatedClass(Category.class);
SessionFactory sessionFactory = cfg.buildSessionFactory();
HibernateTemplate ht = new HibernateTemplate(sessionFactory);
Category a = new Category();
Category b = new Category();
ht.save(a);
ht.save(b);
for (int i = 0; i < 3; i++) {
UcoopThread t = new UcoopThread();
t.setCategory(a);
t.setThreadName("thread+" + i);
ht.save(t);
for (int i = 0; i < 2; i++) {
UcoopThread t = new UcoopThread();
t.setCategory(b);
t.setThreadName("thread-" + i);
ht.save(t);
assert 5 == ht.find("from UcoopThread").size();
assert 3 == ht.find("from UcoopThread as u where u.category.id = ?", a.getId()).size();
assert 2 == ht.find("from UcoopThread as u where u.category.id = ?", b.getId()).size();
System.out.println(ht.find("from UcoopThread"));
}Hope this helps. -
Hibernate query...how to connect two databases...
hi i m new to hibernate..
i created two tables..
1st table is catalog:
2nd table is acctinfo
//HBM file is :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernate.example.Catalog" table="catalog">
<id name="id" type="integer" column="ID">
<generator class="increment"/>
</id>
<property name="journal" type="string" column="JOURNAL"/>
<property name="publisher" type="string" column="PUBLISHER"/>
<property name="edition" type="string" column="EDITION"/>
<property name="title" type="string" column="TITLE"/>
<property name="author" type="string" column="AUTHOR"/>
<bag name="accinfo" cascade="all" >
<key column="ID"/>
<one-to-many class="hibernate.example.Acctinfo"/>
</bag>
</class>
<class name="hibernate.example.Acctinfo" table="acctinfo">
<id name="id" type="integer" column="ID">
<generator class="increment"/>
</id>
<property name="account" type="string" column="ACCOUNT"/>
<property name="password" type="string" column="PASSWORD"/>
<property name="balance" type="string" column="BALANCE"/>
</class>
</hibernate-mapping>
///******************getter setter file is::****************
package hibernate.example;
public class Acctinfo
int id;
String account;
String password;
String balance;
public Acctinfo()
public void setId(int id)
this.id = id;
public int getId()
return id;
public void setAccount(String account)
this.account = account;
public void setPassword(String password)
this.password = password;
public void setBalance(String balance)
this.balance = balance;
public String getAccount()
return account;
public String getBalance()
return balance;
public String getPassword()
return password;
//********************2nd getter setter file is:***********************
package hibernate.example;
import java.util.List;
public class Catalog
int id;
String journal;
String publisher;
String edition;
String title;
String author;
private List accinfo;
public Catalog()
public void setId(int id)
this.id = id;
public int getId()
return id;
public void setJournal(String journal)
this.journal = journal;
public String getJournal()
return journal;
public void setPublisher(String publisher)
this.publisher = publisher;
public String getPublisher()
return publisher;
public void setEdition(String edition)
this.edition = edition;
public String getEdition()
return edition;
public void setTitle(String title)
this.title = title;
public String getTitle()
return title;
public void setAuthor(String author)
this.author = author;
public String getAuthor()
return author;
public void setAccinfo(List accinfo)
this.accinfo = accinfo;
public List getAccinfo()
return accinfo;
* To change this template, choose Tools | Templates
* and open the template in the editor.
package hibernate.example;
import hibernate.example.Acctinfo;
import hibernate.example.Catalog;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class CatalogClient
Session session = null;
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
public static void main(String str[])
CatalogClient clc = new CatalogClient();
//clc.saveData();
//clc.deleteData();
//clc.showData();
clc.updateData();
public void showData()
try
session =sessionFactory.openSession();
String SQL_QUERY ="select id, journal, publisher, edition, title, author from catalog";
// String SQL_QUERY ="select c.ID, c.JOURNAL, c.PUBLISHER, c.EDITION, c.TITLE, c.AUTHOR, a.ACCOUNT, a.PASSWORD,a.BALANCE from catalog c, ACCTINFO a where c.ID = a.ID";
SQLQuery query = session.createSQLQuery(SQL_QUERY);
System.out.println("*** query : *** "+ query);
//for(ListIterator it=query.list().listIterator();it.hasNext();)
for (ListIterator lit = query.list().listIterator(); lit.hasNext();)
Object[] row = (Object[]) lit.next();
/*System.out.println("ID: " + row[0]);
System.out.println("Title: " + row[1]);
System.out.println("Author: " + row[2]);
System.out.println("Isbn: " + row[3]);
System.out.println("Pages: " + row[4]);
System.out.println("Copyright: " + row[5]);
System.out.println("Cost: " + row[6]);
System.out.println("******NEXT****************");
Object[] row = (Object[]) it.next();*/
System.out.println("ID: " + row[0]);
System.out.println("JOURNAL: " + row[1]);
System.out.println("PUBLISHER: " + row[2]);
System.out.println("EDITION: " + row[3]);
System.out.println("TITLE: " + row[4]);
System.out.println("AUTHOR: " + row[5]);
System.out.println("acc: " + row[6]);
System.out.println("pass: " + row[7]);
System.out.println("bal: " + row[8]);
System.out.println("***************************");
session.close();
catch(Exception e)
System.out.println(e.getMessage());
public void saveData()
session =sessionFactory.openSession();
Transaction transaction = null;
transaction = session.beginTransaction();
Catalog catalog = setBean();
//System.out.println("before save");
session.save(catalog);
//System.out.println("after save");
transaction.commit();
session.flush();
session.close();
public void updateData()
session =sessionFactory.openSession();
Catalog catalog = new Catalog();
catalog.setId(2);
catalog.setAuthor("manoj");
catalog.setJournal("java");
catalog.setEdition("1st");
catalog.setPublisher("indiabulls");
catalog.setTitle("java Servlet");
session.update(catalog);
session.flush();
session.close();
public void deleteData()
session =sessionFactory.openSession();
Catalog catalog = new Catalog();
catalog.setId(3);
session.delete(catalog);
session.flush();
session.close();
public static Catalog setBean()
Acctinfo accinfo = new Acctinfo();
accinfo.setAccount("MANOJ1");
accinfo.setPassword("orbis");
accinfo.setBalance("1000");
List list = new ArrayList();
list.add(accinfo);
Catalog catalog = new Catalog();
catalog.setJournal("india");
catalog.setPublisher("indiabulls");
catalog.setEdition("ist");
catalog.setTitle("orbis");
catalog.setAuthor("manoj");
catalog.setAccinfo(list);
return catalog;
//********************CFG FILE IS ******************
<?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 name="session">
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@172.16.31.25:1521:BOMBAY</property>
<property name="hibernate.connection.username">mumbai</property>
<property name="hibernate.connection.password">mumbai123</property>
<!-- Set AutoCommit to true -->
<property name="connection.autocommit">true</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
<!-- Mapping files -->
<mapping resource="Catalog.hbm.xml"/>
</session-factory>
</hibernate-configuration>
**********************error i m facing is :************************
0 [main] WARN net.sf.ehcache.config.Configurator - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/Documents%20and%20Settings/d.poonam/Desktop/hibernate/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
1188 [main] WARN org.hibernate.impl.SessionFactoryObjectFactory - Could not bind factory to JNDI
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getNameParser(Unknown Source)
at org.hibernate.util.NamingHelper.bind(NamingHelper.java:52)
at org.hibernate.impl.SessionFactoryObjectFactory.addInstance(SessionFactoryObjectFactory.java:90)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:247)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1043)
at hibernate.example.CatalogClient.<init>(CatalogClient.java:24)
at hibernate.example.CatalogClient.main(CatalogClient.java:27)
please help me out....
thanks in advance..
if u know how to connect two tables plz let me know..
its urgent....I made this work with MySQL. Adapt to your situation as needed. - %
package hibernate.model;
import hibernate.util.HibernateUtils;
import hibernate.model.Catalog;
import hibernate.model.Account;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import hibernate.util.HibernateUtils;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
public class CatalogTest
private static final Log LOGGER = LogFactory.getLog(CatalogTest.class);
public static void main(String[] args)
Session session = null;
try
session = HibernateUtils.getSessionFactory().getCurrentSession();
session.beginTransaction();
int rowsBefore = HibernateUtils.getRowCount(session, Catalog.class);
assertEquals("should not have any Catalogs", rowsBefore, 0);
Catalog catalog = new Catalog("test title");
catalog.addAccount(new Account(100));
catalog.addAccount(new Account(200));
Long id = (Long) session.save(catalog);
assertNotNull("generated id should not be null", id);
LOGGER.info("returned id: " + id);
session.getTransaction().commit();
LOGGER.debug("transaction committed");
catch (Exception e)
LOGGER.error(e);
session.getTransaction().rollback();
package hibernate.model;
import java.io.Serializable;
import java.text.NumberFormat;
public class Account implements Serializable
private Long id;
private int balance;
public Account()
this(null, 0);
public Account(int balance)
this(null, balance);
public Account(Long id, int balance)
this.id = id;
this.balance = balance;
public Long getId()
return id;
private void setId(Long id)
this.id = id;
public int getBalance()
return balance;
private void setBalance(int balance)
this.balance = balance;
public boolean equals(Object o)
if (this == o)
return true;
if (!(o instanceof Account))
return false;
Account account = (Account) o;
return !(id != null ? !id.equals(account.id) : account.id != null);
public int hashCode()
int result;
result = (id != null ? id.hashCode() : 0);
result = 31 * result + balance;
return result;
public String toString()
return new StringBuilder().append("Account{").append("id=").append(id).append(", balance=").append(NumberFormat.getCurrencyInstance().format(balance)).append('}').toString();
<?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 package="hibernate.model" default-access="field" default-lazy="true">
<class name="Account" table="accounts">
<id name="id" column="account_id">
<generator class="native"/>
</id>
<property name="balance" column="balance"/>
</class>
</hibernate-mapping>
package hibernate.model;
import java.io.Serializable;
import java.util.Set;
import java.util.HashSet;
import java.util.Collections;
public class Catalog implements Serializable
private Long id;
private String title;
private Set<Account> accounts;
public Catalog()
this(null, "", Collections.EMPTY_SET);
public Catalog(String title)
this(null, title, Collections.EMPTY_SET);
public Catalog(Long id, String title, Set<Account> accounts)
this.id = id;
this.title = title;
this.accounts = new HashSet<Account>(accounts);
public Long getId()
return id;
private void setId(Long id)
this.id = id;
public String getTitle()
return title;
private void setTitle(String title)
this.title = title;
public Set<Account> getAccounts()
return accounts;
private void setAccounts(Set<Account> accounts)
this.accounts = accounts;
public void addAccount(Account account)
this.getAccounts().add(account);
public void removeAccount(Account account)
this.getAccounts().remove(account);
public boolean equals(Object o)
if (this == o)
return true;
if (!(o instanceof Catalog))
return false;
Catalog catalog = (Catalog) o;
return !(id != null ? !id.equals(catalog.id) : catalog.id != null);
public int hashCode()
return (id != null ? id.hashCode() : 0);
public String toString()
return new StringBuilder().append("Catalog{").append("id=").append(id).append(", title='").append(title).append('\'').append(", accounts=").append(accounts).append('}').toString();
<?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 package="hibernate.model" default-access="field" default-lazy="true">
<class name="Catalog" table="catalogs">
<id name="id" column="catalog_id">
<generator class="native"/>
</id>
<property name="title" column="title"/>
<set name="accounts" cascade="all">
<key column="catalog_id"/>
<one-to-many class="hibernate.model.Account"/>
</set>
</class>
</hibernate-mapping>
<!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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate?autoReconnect=true</property>
<property name="connection.username">hibernate</property>
<property name="connection.password">hibernate</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">true</property>
<property name="generate_statistics">true</property>
<property name="query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="cache.use_minimal_puts">false</property>
<property name="cache.use_query_cache">false</property>
<property name="order_updates">false</property>
<property name="hbm2ddl.auto">create-drop</property>
<property name="current_session_context_class">thread</property>
<mapping resource="hibernate/persistence/hibernate/Account.hbm.xml"/>
<mapping resource="hibernate/persistence/hibernate/Catalog.hbm.xml"/>
</session-factory>
</hibernate-configuration> -
Trouble connecting to MSSQL through Hibernate
HI All,
below is my hibernate.cfg.xml file
<?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">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://1.234.456.789:1433/hibernatetutorial</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">dborad</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect </property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I am getting the below error
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Inserting Record
Done
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:82)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:70)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.AbstractBatcher.openConnection(AbstractBatcher.java:384)
at org.hibernate.jdbc.JDBCContext.connect(JDBCContext.java:141)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:88)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:73)
at org.hibernate.jdbc.AbstractBatcher.prepareStatement(AbstractBatcher.java:66)
at org.hibernate.jdbc.AbstractBatcher.prepareBatchStatement(AbstractBatcher.java:130)
at org.hibernate.persister.entity.BasicEntityPersister.insert(BasicEntityPersister.java:1809)
at org.hibernate.persister.entity.BasicEntityPersister.insert(BasicEntityPersister.java:2171)
at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:46)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:239)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:223)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:136)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:274)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:669)
at roseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:36)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The port number 1433/hibernatetutorial is not valid.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:580)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.AbstractBatcher.openConnection(AbstractBatcher.java:381)
... 15 more
And below is the FirstExample.java
package roseindia.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
* @author Deepak Kumar
* http://www.roseindia.net
* Hibernate example to inset data into Contact table
public class FirstExample {
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("praveen");
contact.setLastName("Kumar");
contact.setEmail("[email protected]");
session.save(contact);
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
// Actual contact insertion will happen at this step
session.flush();
session.close();
<property name="hibernate.connection.url">jdbc:sqlserver://1.234.456.789:1433/hibernatetutorial</property>
hibernatetutorial is the database name i have created on the database.
<?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="roseindia.tutorial.hibernate.Contact" table="CONTACT">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
<class name="roseindia.tutorial.hibernate.Book" table="book">
<id name="lngBookId" type="long" column="id" >
<generator class="increment"/>
</id>
<property name="strBookName">
<column name="bookname" />
</property>
</class>
<class name="roseindia.tutorial.hibernate.Insurance" table="insurance">
<id name="lngInsuranceId" type="long" column="ID" >
<generator class="increment"/>
</id>
<property name="insuranceName">
<column name="insurance_name" />
</property>
<property name="investementAmount">
<column name="invested_amount" />
</property>
<property name="investementDate">
<column name="investement_date" />
</property>
</class>
</hibernate-mapping>
The above is the contact.hbm.xml
Pls help me out, its Urgent
Edited by: PraveenKJain on May 17, 2010 2:35 AMWhen i try inserting a file using the below program its getting stored in the database as null values.
package roseindia.tutorial.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class FirstExample {
public static void main(String[] args) {
Session session = null;
try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
//Create new instance of Contact and set values in it by reading them from form object
System.out.println("Inserting Record");
Contact contact = new Contact();
contact.setId(6);
contact.setFirstName("Anonymous");
contact.setLastName("nothing");
contact.setEmail("[email protected]");
session.save(contact);
System.out.println("ID : "+contact.getId() + "\n" + "Name " + ": " + contact.getFirstName()); // this is getting printed fine
System.out.println("Done");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
session.flush();// here null values are getting passed to the contact table
System.out.println("Insert Done");
session.close();
The contact.hbm.xml file
<?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="roseindia.tutorial.hibernate.Contact" table="CONTACT">
<id name="id" type="long" column="ID" >
<generator class="assigned"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
</hibernate-mapping>
The 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">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://1.1.1.1:1039;databaseName=MyDB</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">dborad</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect </property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The Output :
Inserting Record
ID : 6
Name : Anonymous
Done
Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?) //(why are those null values getting passed)
Insert Done
Edited by: PraveenKJain on May 17, 2010 5:49 AM
Maybe you are looking for
-
Display a sum of a column(field) in the view
Hi I would like to show the sum of a revenue field(currency) in any view of the opportunity entity(only when revenue field exist in the view) , may be at the end of the view or as a alert message on button click., but sum should change dynamically ba
-
Problems displaying images on sites
i am using an addon that allows me to drag and drop links and open them in different tabs. whenever i try to drag and drop a image file from my facebook the tab will open but nothing is displayed. i know the page has loaded because i can see the curs
-
Bandwidth Video Freeze and Switching Subscribers
Hi, How much upload speed to you need to have to ensure a smooth video playback. We also have a Multi Subscriber setup. So sometimes we want a user to be in the big cam. But then switc them to one of the samller subscribers (3 subscribers in all) Thi
-
I have tried all sugestions for how to charge my ipad 2 that no longer charges, and nothing seems to work, can anyone offer any new advise?
-
We just released the After Effects CS6 (11.0.2) update. There are a lot of bug fixes and additions in this update. See this page for details: http://adobe.ly/AE1102 Let us know if you have any trouble with this update.