6

I am new to hibernate.I am developing a struts application where i want to integerate hibernate.I am using SQL Server 2008 R2 as database.I have configured my hibernate configuration file and used annotations based entities.When i try to run my hibernate configuration file,I get this below error :

Error

12:49:41.752 [main] DEBUG org.hibernate.util.DTDEntityResolver - trying to resol
ve system-id [http://hibernate.org/dtd/hibernate-configuration-3.0.dtd]
Initial SessionFactory creation failed.org.hibernate.HibernateException: Could n
ot parse configuration: hibernate.cfg.xml

I have given my files below :

DAOImpl

package com.myProj.dao.impl;

import java.util.logging.Logger;

import com.googlecode.s2hibernate.struts2.plugin.annotations.SessionTarget;
import com.googlecode.s2hibernate.struts2.plugin.annotations.TransactionTarget;
import com.myProj.dao.StudentDetailsDAO;
import com.myProj.entity.StudentDetails;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class StudentDetailsDAOImpl implements StudentDetailsDAO{

    Logger LOGGER;
    @SessionTarget
    Session session;
    @TransactionTarget
    Transaction transaction;
    @Override
    public void saveOrUpdateStudentDetail(StudentDetails studDetails) {
        try{
            session.saveOrUpdate(studDetails);
        }catch(Exception e){
            transaction.rollback();
            LOGGER.info("StudentDetailsDAOImpl : saveOrUpdateStudentDetail : Exception "+e.toString());
        }

    }

}

StudentDetails.java

package com.myProj.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="dbo.student_details")
public class StudentDetails {
@Id
@GeneratedValue
@Column(name="id")
private int id;

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

@Column(name="grade")
private String grade;

@Column(name="dob")
private String dob;

@Column(name="stud_address")
private String stud_address;

@Column(name="stud_language")
private String stud_language;

@Column(name="student_marks_id")
private StudentMarks studentMarks;

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;
}

public String getGrade() {
    return grade;
}

public void setGrade(String grade) {
    this.grade = grade;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public String getStud_address() {
    return stud_address;
}

public void setStud_address(String stud_address) {
    this.stud_address = stud_address;
}

public String getStud_language() {
    return stud_language;
}

public void setStud_language(String stud_language) {
    this.stud_language = stud_language;
}

public StudentMarks getStudentMarks() {
    return studentMarks;
}

public void setStudentMarks(StudentMarks studentMarks) {
    this.studentMarks = studentMarks;
}
}

StudentMark.java

package com.myProj.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="dbo.student_marks")
public class StudentMarks {
    @Id
    @GeneratedValue
    @Column(name="id")
    private int id;

@Column(name="english")
private int english;

@Column(name="physics")
private int physics;

@Column(name="chemistry")
private int chemistry;

@Column(name="biology")
private int biology;

@Column(name="maths")
private int maths;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public int getEnglish() {
    return english;
}
public void setEnglish(int english) {
    this.english = english;
}
public int getPhysics() {
    return physics;
}
public void setPhysics(int physics) {
    this.physics = physics;
}
public int getChemistry() {
    return chemistry;
}
public void setChemistry(int chemistry) {
    this.chemistry = chemistry;
}
public int getBiology() {
    return biology;
}
public void setBiology(int biology) {
    this.biology = biology;
}
public int getMaths() {
    return maths;
}
public void setMaths(int maths) {
    this.maths = maths;
}

}

HibernateUtil.java

package com.myProj.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.myProj.entity.StudentDetails;

public class HibernateUtil {

private static final SessionFactory sessionFactory;

static {
    try {
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(StudentDetails.class);



        config.configure("hibernate.cfg.xml");
    //new SchemaExport(config).create(true,true);

        sessionFactory = config.buildSessionFactory();

    } catch (Throwable ex) {
        // Log the exception. 
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
}

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.org/dtd/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://<myIp>:1433;databaseName=<myDatabase></property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.myProj.entity.StudentDetails" ></mapping>
        <mapping class="com.myProj.entity.StudentMarks" ></mapping>
    </session-factory>
</hibernate-configuration>

I have given below the list of jar files that i am using :

commons-beanutils-1.8.0.jar
commons-chain-1.2.jar
commons-digester-2.1.jar
hibernate-3.5.3.jar
javax.servlet-3.0.jar
logback-classic-0.9.6.jar
logback-core-0.9.6.jar
ognl-3.0.6.jar
slf4j-api-2.0.99.jar
slf4j-log4j13-1.0.1.jar
sqljdbc-1.2.0.jar
struts-core-1.3.10.jar
struts-taglib-1.3.10-sources.jar
struts-taglib-1.3.5.jar
struts2-core-2.3.8.jar
struts2-json-plugin-2.3.8.jar
struts2-tiles-plugin-2.1.8.1.jar
xwork-2.0.4.jar
xwork-core-2.3.12.jar

Also when i check my apache server i get the following error in it

Apache Server log

java.lang.ExceptionInInitializerError
    at com.myProj.util.HibernateUtil.<clinit>(HibernateUtil.java:27)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3744)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4252)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:448)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
    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:597)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)
Caused by: org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1586)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:1212)
    at org.hibernate.cfg.AnnotationConfiguration.doConfigure(AnnotationConfiguration.java:107)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1520)
    at org.hibernate.cfg.AnnotationConfiguration.configure(AnnotationConfiguration.java:1194)
    at com.myProj.util.HibernateUtil.<clinit>(HibernateUtil.java:19)
    ... 21 more
Caused by: org.dom4j.DocumentException: hibernate.org Nested exception: hibernate.org
    at org.dom4j.io.SAXReader.read(SAXReader.java:484)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1576)
    ... 26 more
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Is your `databaseName=` the real value in your file or just a placeholder? – Alessandro Da Rugna May 05 '17 at 08:38
  • Actually i am using the real ip and database values in both and fields.I just did not want to reveal the ip nor database int this forum because its a confidential information – Deepak Ramakrishnan Kalidass May 05 '17 at 09:22
  • Can you step with a debugger into `at org.hibernate.cfg.Configuration.configure(Configuration.java:1520)` and see what happens? I spot a space character before jdbc ` jdbc:sqlserver:` can you try to delete it? – Alessandro Da Rugna May 05 '17 at 09:54
  • Tried removing that space inside connection.url tag.But still no change. – Deepak Ramakrishnan Kalidass May 05 '17 at 10:08
  • Looking the source code https://github.com/hibernate/hibernate-orm/blob/3.5/core/src/main/java/org/hibernate/cfg/Configuration.java#L1576 looks something related to mapping the entities. Can you attach the debugger and see what happens during startup of the application? – Alessandro Da Rugna May 05 '17 at 10:20
  • Thats one more problem.I am using eclipse currently so i am not able to debug the Configuration.java‌​:1520 since its inside hibernate-3.5.3.jar and i am not able to proceed forward – Deepak Ramakrishnan Kalidass May 05 '17 at 11:45

4 Answers4

2

I have finally found out what is wrong.But not sure why it didnt work.I changed the below line in my configuration file

<!DOCTYPE hibernate-configuration  PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

to

 <!DOCTYPE hibernate-configuration SYSTEM "classpath://com/myProj/util/hibernate-configuration-3.0.dtd">

and had placed the file hibernate-configuration-3.0.dtd in the package com.myProj.util.Now this configuration file is running as gem and the session is created.

  • 1
    Good! But remember, you must the same align struts2 libraries to the same one, possibly the latest one, don't avoid doing it only because you've found this bug – Andrea Ligios May 08 '17 at 12:03
1

I have given below the list of jar files that i am using :

commons-beanutils-1.8.0.jar
commons-chain-1.2.jar
commons-digester-2.1.jar
hibernate-3.5.3.jar
javax.servlet-3.0.jar
logback-classic-0.9.6.jar
logback-core-0.9.6.jar
ognl-3.0.6.jar
slf4j-api-2.0.99.jar
slf4j-log4j13-1.0.1.jar
sqljdbc-1.2.0.jar
struts-core-1.3.10.jar
struts-taglib-1.3.10-sources.jar
struts-taglib-1.3.5.jar
struts2-core-2.3.8.jar
struts2-json-plugin-2.3.8.jar
struts2-tiles-plugin-2.1.8.1.jar
xwork-2.0.4.jar
xwork-core-2.3.12.jar

This is the biggest pile of garbage I've ever seen in years.

  1. Only put what you need (and before knowing if you need it or not, you need to know what every jar does), beginning by dropping every Struts 1 jar;
  2. Preserve the consistency of the versions: every Struts2 jar must have the same version, you can't have 2.3.8 with 2.3.12 with 2.1.8.1... what-the-heck ?
  3. Always use the latest version (2.3.32), or you're vulnerable to CRITICAL issues and your server will most likely be hacked in minutes. Small refactors could be needed, but believe me, it's your best option.

Use Maven that will do it for you, or do it manually cum grano salis, or do it manually, but at the end you should have the following lsit of libraries in your project:

        struts2-core-2.3.32.jar
          xwork-core-2.3.32.jar
struts2-tiles-plugin-2.3.32.jar
 struts2-json-plugin-2.3.32.jar

                ognl-3.0.19.jar
          freemarker-2.3.22.jar

             log4j-core-2.3.jar
       log4j-slf4j-impl-2.3.jar <-- optional
           slf4j-api-1.7.25.jar <-- optional

Plus the ones you've not shown us (asm3.3m, asm5.0.2, etc...). But seriously, stop a minute and run a Maven archetype for 2.3.32, it will generate an empty project for you and import all the right libraries; then you can take those libraries and put them in your ant-based project (or whatever it is), but don't do this annoying and highly unproductive work manually.

After that, I guess your Hibernate will work.


At that point, however, if you're runnign in a Java EE container (Jboss, Wildfly, Weblogic, Glassfish, TomEE), you should consider migrating from mixed Hibernate / JPA2 (javax.persistence annotations), to full JPA2.

JPA2 is the standard persistence layer in Java EE 6+. It's described in JSR-317 (JPA 2.0) and JSR-338 (JPA 2.1), and it defines a standard and reliable way of handling the persistence. It does not provide an implementation, so you are free to choose the implementation you prefer (eg. Hibernate).

Just use only javax.persistence annotations, and not a single org.hibernate annotation, and you'll be going full JPA2, even if using Hibernate.

That way, many things (like session factories) will not even be needed anymore: almost everything will be handled by the container automatically (but you'll be able to choose to handle transactions manually, if you want), and simply injecting an EntityManager with the @PersistenceContext annotation, through an automatically handled EntityManagerFactory.


Note 1: you don't need to specify the column name if it is identical to the variable name:

@Column(name="the_name") // needed
private String name;

//@Column(name="name") // not needed
@Column                // this is enough
private String name;

Note 2: you can automate the camelCase to snake_case variable-to-column conversion by simply inserting a property in the persistence.xml (the JPA version of hibernate.cfg.xml, almost identical), so fullName variable will be translated to full_name on the database without the need to specify it in the @Column annotation.

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
0

The problem is hibernate.cfg.xml

<property name="hibernate.connection.url">
jdbc:sqlserver://<myIp>:1433;databaseName=<myDatabase>
</property>

Replace <myIp> and <myDatabase> with proper values

StanislavL
  • 56,971
  • 9
  • 68
  • 98
  • Actually i am using the real ip and database values in both and fields.I just did not want to reveal the ip nor database name because its a confidential information. – Deepak Ramakrishnan Kalidass May 05 '17 at 09:21
  • 1
    The error states hibernate.cfg.xml is not valid. There is something wrong with the xml. Try to figure out what exactly is wrong. – StanislavL May 05 '17 at 09:23
  • Ya i am pretty sure that the problem is with either hibernate.cfg.xml file or the jars.But when i check the configuration file it looks perfect to me.I have no clue whats going wrong in that file – Deepak Ramakrishnan Kalidass May 05 '17 at 09:49
0

As StanislavL mentioned,the problem is with how properties [ myIp , myDatabase ] are mentioned as xml tags. That causes xml parsing exception.

since you are not using spring, it seems the best bet you have is to set properties at run time. please refer these links - hibernate.cfg.xml - Set parameters from a properties file

check out the answer "You can do it programmatically" - How to include properties from external file to hibernate.cfg.xml?

Community
  • 1
  • 1
jshcode
  • 181
  • 2
  • no actually in the actual code i have given the ip and database names instead of those tags.Since i did not want to display those details i have given those items as tags.Still i get parsing exception – Deepak Ramakrishnan Kalidass May 05 '17 at 17:34