Mapping (RESOURCE) not found - java

Guys I am new with Hibernate and I am struggling to make a hello world app work. Below I will post the exception I am getting as well as my code - with the hope maybe someone can spot other errors which I have and save me from "future" troubles.
Code:
package org.arpit.javapostsforlearning;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity(name = "User_table")
public class User {
#Id
int userId;
#Column(name = "User_Name")
String userName;
String userMessage;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
}
This:
package org.arpit.javapostsforlearning;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateMain {
public static void main(String[] args)
{
Configuration configuration=new Configuration();
configuration.configure();
configuration.addClass(org.arpit.javapostsforlearning.User.class);
ServiceRegistry sr= new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sf=configuration.buildSessionFactory(sr);
User user1=new User();
user1.setUserName("Arpit");
user1.setUserMessage("Hello world from arpit");
User user2=new User();
user2.setUserName("Ankita");
user2.setUserMessage("Hello world from ankita");
Session ss=sf.openSession();
ss.beginTransaction(); //saving objects to session
ss.save(user1);
ss.save(user2);
ss.getTransaction().commit();
ss.close();
}
}
And XMLS:
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://localhost:1433;database=Sandboxlearning;integratedSecurity=true</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.SQLServer2005Dialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
User.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="User_table">
<meta attribute="class-description">
This class contains the user detail.
</meta>
<id name="userId" type="int" column="userId">
<generator class="native"/>
</id>
<property name="userName" column="User_Name" type="string"/>
<property name="userMessage" column="userMessage" type="string"/>
</class>
</hibernate-mapping>
Exception:
Jun 28, 2016 7:17:15 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.0.Final}
Jun 28, 2016 7:17:15 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 28, 2016 7:17:15 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 28, 2016 7:17:15 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Exception in thread "main" org.hibernate.boot.MappingNotFoundException: Mapping (RESOURCE) not found : org/arpit/javapostsforlearning/User.hbm.xml : origin(org/arpit/javapostsforlearning/User.hbm.xml)
at org.hibernate.boot.spi.XmlMappingBinderAccess.bind(XmlMappingBinderAccess.java:56)
at org.hibernate.boot.MetadataSources.addResource(MetadataSources.java:274)
at org.hibernate.boot.MetadataSources.addClass(MetadataSources.java:262)
at org.hibernate.cfg.Configuration.addClass(Configuration.java:513)
at org.arpit.javapostsforlearning.HibernateMain.main(HibernateMain.java:14)
The XMLS are stored under src folder.
Here is also screen shot of my App
image

Take a look to: <mapping class="User.hbm.xml"/>. But you using resource. You are able to use class when you saying that map me class for that, but you want to map resource. So just use
<mapping resource="User.hbm.xml"/>

Related

i am Getting org.hibernate.InvalidMappingException: Unable to read XML while running simple hibernate project

I'm running my first hibernate project which saves user information such as id,name and address into mysql database
This is my error log
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.InvalidMappingException: Unable to read XML
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:109)
at org.hibernate.cfg.Configuration.add(Configuration.java:490)
at org.hibernate.cfg.Configuration.add(Configuration.java:486)
at org.hibernate.cfg.Configuration.add(Configuration.java:659)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:742)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2197)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2169)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2149)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2102)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2017)
at mypack.DataInsertion.insertInfo(DataInsertion.java:18)
at mypack.DataInsertion.main(DataInsertion.java:11)
Caused by: org.dom4j.DocumentException: Error on line 3 of document : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:78)
... 11 more
hibernate.cfg.xml (Configuration xml file)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibdb</property>
<property name="connection.user">root</property>
<property name="connection.password">admin</property>
<!-- Related to the connection END -->
<!-- Related to the hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Related to the hibernate properties END -->
<!-- List of XML mapping files -->
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
user.hbm.xml (Mapping xml)
<!-- Mapping File to POJO Class -->
<?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="mypack.DataProvider" table="user_info">
<id name="user_id" column="table_id">
<generator class="assigned"/>
</id>
<property name="user_name" column = "name" />
<property name="user_address" column = "address" />
</class>
</hibernate-mapping>
DataProvider.java (POJO class)
//POJO Class
package mypack;
public class DataProvider {
private int user_id;
private String user_name;
private String user_address;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
}
DataInsertion.java (Implentation java class)
package mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DataInsertion {
public static void main(String[] args) {
new DataInsertion().insertInfo();
}
public void insertInfo()
{
Configuration con = new Configuration(); //interation with hib
con.configure("hibernate.cfg.xml"); //registering to xml
SessionFactory SF = con.buildSessionFactory(); //creating session
Session session = SF.openSession(); //opening new session
DataProvider provider = new DataProvider();
provider.setUser_id(1);
provider.setUser_name("Goutham");
provider.setUser_address("Hunsur");
Transaction TR = session.beginTransaction();
session.save(provider);
System.out.println("Object saved successfully");
TR.commit(); //saving transaction
session.close();
SF.close();
}
}
Please advise me,,,
Thanks.
Try removing the comment line and blank line before the first tag in user.hbm.xml

Could not instantiate persister org.hibernate.persister.entity.JoinedSubclassEntityPersister

I am getting the following error while trying to connect to mysql using hibernate. I have a Super class Employee and three subclasses: SoftwareEmployee, HardWareEmployee and Admin.I also have two xml files: hibernateisapersubclass.cfg.xml and employeeisapersubclass.hbm.xml. I am trying to populate data in 4 different table using 'joined-subclass' tag in my xml. Please help.
Error that I am getting are as follows:
Dec 04, 2016 7:45:34 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.5.Final}
Dec 04, 2016 7:45:34 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 04, 2016 7:45:34 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/hqlstudent]
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Dec 04, 2016 7:45:35 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sun Dec 04 19:45:35 EST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Dec 04, 2016 7:45:35 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Dec 04, 2016 7:45:36 PM org.hibernate.AssertionFailure <init>
ERROR: HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: Table hqlstudent.superemployee not found
Dec 04, 2016 7:45:36 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost/hqlstudent]
Exception in thread "main" org.hibernate.MappingException: Could not instantiate persister org.hibernate.persister.entity.JoinedSubclassEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:112)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:128)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:297)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at test.ClientIsAPerSubClass.main(ClientIsAPerSubClass.java:22)
Caused by: org.hibernate.AssertionFailure: Table hqlstudent.superemployee not found
at org.hibernate.persister.entity.AbstractEntityPersister.getTableId(AbstractEntityPersister.java:5168)
at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:433)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 7 more
Following are my five java files and two xml files:
ClientIsAPerSubClass.java
package test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import beans.Admin;
import beans.Admin1;
import beans.HardwareEmployee;
import beans.HardwareEmployee1;
import beans.SoftwareEmployee;
import beans.SoftwareEmployee1;
public class ClientIsAPerSubClass {
public static void main(String [] args){
Configuration configuration = new Configuration();
configuration.configure("resources/hibernateisapersubclass.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction= session.beginTransaction();//student object will move database;
SoftwareEmployee1 softwareEmployee= new SoftwareEmployee1();
softwareEmployee.setId(1);
softwareEmployee.setName("bishwash");
softwareEmployee.setEmail("20wash.sharma#gmail.com");
softwareEmployee.setSalary(60000);
softwareEmployee.setTool("hibernate");
HardwareEmployee1 hardwareEmployee = new HardwareEmployee1();
hardwareEmployee.setId(2);
hardwareEmployee.setName("mahendra");
hardwareEmployee.setEmail("mahendra#mahendra.com");
hardwareEmployee.setSalary(55000);
hardwareEmployee.setWorkinghour(20);
Admin1 admin= new Admin1();
admin.setId(3);
admin.setName("ashish#ashish.com");
admin.setEmail("mahendra#mahendra.com");
admin.setSalary(60000);
admin.setBranchname("Kathmandu");;
session.save(softwareEmployee);
session.save(hardwareEmployee);
session.save(admin);
transaction.commit();
session.close();
sessionFactory.close();
//System.out.println("no of rows dumped from old to new table"+i);
}
}
Admin.java
package beans;
public class Admin extends Employee {
private String branchname;
public Admin() {
}
public Admin(int id, String name, String email, double salary, String branchname) {
super(id, name, email, salary);
this.branchname= branchname;
}
public String getBranchname() {
return branchname;
}
public void setBranchname(String branchname) {
this.branchname = branchname;
}
}
package beans;
public class HardwareEmployee extends Employee {
private int workinghour;
public HardwareEmployee() {
super();
// TODO Auto-generated constructor stub
}
public HardwareEmployee(int id, String name, String email, double salary, int workinghour) {
super(id, name, email, salary);
this.workinghour= workinghour;
}
public int getWorkinghour() {
return workinghour;
}
public void setWorkinghour(int workinghour) {
this.workinghour = workinghour;
}
}
SoftwareEmployee.java
package beans;
public class SoftwareEmployee extends Employee {
private String tool;
public SoftwareEmployee() {
super();
// TODO Auto-generated constructor stub
}
public SoftwareEmployee(int id, String name, String email, double salary ,String tool) {
super(id, name, email, salary);
this.tool= tool;
}
public String getTool() {
return tool;
}
public void setTool(String tool) {
this.tool = tool;
}
}
HardwareEmployee.java
package beans;
public class HardwareEmployee extends Employee {
private int workinghour;
public HardwareEmployee() {
super();
// TODO Auto-generated constructor stub
}
public HardwareEmployee(int id, String name, String email, double salary, int workinghour) {
super(id, name, email, salary);
this.workinghour= workinghour;
}
public int getWorkinghour() {
return workinghour;
}
public void setWorkinghour(int workinghour) {
this.workinghour = workinghour;
}
}
employeeisapersubclass.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="beans.Employee" table ="superemployee" schema="hqlstudent">
<id name="id"/>
<property name="name" />
<property name="email" />
<property name="salary" />
<joined-subclass name="beans.SoftwareEmployee" table="softwareemployee">
<key column ="id"/>
<property name="tool"/>
</joined-subclass>
<joined-subclass name="beans.HardwareEmployee" table="hardwareemployee">
<key column ="id"/>
<property name="workinghour"/>
</joined-subclass>
<joined-subclass name="beans.Admin" table="admin">
<key column ="id"/>
<property name="branchname"/>
</joined-subclass>
</class>
</hibernate-mapping>
hibernateisapersubclass.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.hbm2ddl.auto">
create
</property>
<property name="hibernate.show_sql">
true
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume customstudent is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/hqlstudent
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
password
</property>
<mapping resource="resources/employeeisapersubclass.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Hibernate not connecting with MySql

Stuck at this place I am new to hibernate and making a sample code after watching tutorial However I am stuck connecting hibernate with MySql.
Here is hibernate.cfg.xml placed in the source folder
<?xml version='1.0' encoding='utf-8'?>
<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License:
GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the
lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<hibernate-configuration
xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration
hibernate-configuration-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider
</property>
<property name="current_session_context_class">thread</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="com.javapapers.UserDetails" />
</session-factory>
</hibernate-configuration>
And here is my HibernateTest.java file
package com.javapapers;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user=new UserDetails();
user.setUserId(1);
user.setUserName("Mannu");
System.out.println("Here");
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
System.out.println("Not even printed");
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
Here is UserDetails.java
package com.javapapers;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class UserDetails {
#Id
private int userId;
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
And Here is Error Report
Here
Nov 11, 2015 2:23:03 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.2.Final}
Nov 11, 2015 2:23:03 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Nov 11, 2015 2:23:03 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 10 and column 56 in RESOURCE hibernate.cfg.xml. Message: cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at org.hibernate.cfg.Configuration.configure(Configuration.java:259)
at org.hibernate.cfg.Configuration.configure(Configuration.java:245)
at com.javapapers.HibernateTest.main(HibernateTest.java:15)
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 10; columnNumber: 56; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:420)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:401)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:374)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
... 6 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 10; columnNumber: 56; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1906)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(ValidatorHandlerImpl.java:570)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(ValidatingUnmarshaller.java:86)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:60)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleStartElement(StAXEventConnector.java:246)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(StAXEventConnector.java:115)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:398)
... 8 more
Create SessionFactory like that. It worked at Hibernate 4.3.
Configuration configuration = new Configuration();
configuration.configure();
private static ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
private static SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
And it's total violation of factory pattern to do that in main. Make separate class for it.

org.hibernate.InvalidMappingException: Unable to read XML

i need help with hibernate mapping one-to-many
i don´t know why this is wrong
public class Direccion {
private long id;
private String calle;
private int numero;
private List<Persona> habitantes;
public Direccion(){
}
public Direccion(long id, String calle, int numero, List<Persona> habitante) {
super();
this.id = id;
this.calle = calle;
this.numero = numero;
this.habitantes = habitante;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCalle() {
return calle;
}
public void setCalle(String calle) {
this.calle = calle;
}
public int getNumero() {
return numero;
}
public void setNumero(int numero) {
this.numero = numero;
}
public List<Persona> getHabitantes() {
return habitantes;
}
public void setHabitantes(List<Persona> habitantes) {
this.habitantes = habitantes;
}
#Override
public String toString() {
return "Direccion [id=" + id + ", calle=" + calle + ", numero="
+ numero + ", habitantes=" + habitantes + "]";
}
}
another class:
public class Persona {
private long id;
private long nombre;
public Persona(){
}
public Persona(long id, long nombre) {
super();
this.id = id;
this.nombre = nombre;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getNombre() {
return nombre;
}
public void setNombre(long nombre) {
this.nombre = nombre;
}
#Override
public String toString() {
return "Persona [id=" + id + ", nombre=" + nombre + "]";
}
}
the mapping
<?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="datos.Direccion" table="direccion">
<id column="id" name="id">
<generator class="identity">
</generator>
</id>
<property column="calle" name="calle" type="string" />
<property name="numero" column="numero" type="int" />
<set name="habitantes" table="persona" inverse="true" lazy="true" fetch="select">
<key>
<column name="idPersona" not-null="true" />
</key>
<one-to-many class="datos.Persona" />
</class>
</hibernate-mapping>
another mapping:
<?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="datos.Persona" table="persona">
<id column="id" name="id">
<generator class="identity"/>
</id>
<property column="nombre" name="nombre" type="string" />
<many-to-one name="direccion" class="datos.Direccion" column="idPersona" not-null="true"/>
</set>
</class>
</hibernate-mapping>
hibernate configuration
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD
3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/repasohibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property> <!-- en true muestra hql en consola -->
<!--Mapeo Entidades -->
<mapping resource="mapeos/persona.hbm.xml" />
<mapping resource="mapeos/direccion.hbm.xml" />
</session-factory>
</hibernate-configuration>
this is the error:
jun 21, 2014 6:11:51 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
jun 21, 2014 6:11:51 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.9.Final}
jun 21, 2014 6:11:51 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
jun 21, 2014 6:11:51 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
jun 21, 2014 6:11:51 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
jun 21, 2014 6:11:51 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
jun 21, 2014 6:11:51 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
jun 21, 2014 6:11:51 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: mapeos/persona.hbm.xml
jun 21, 2014 6:11:51 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
ERROR en la inicialización de la SessionFactory: org.hibernate.InvalidMappingException: Unable to read XML
Exception in thread "main" java.lang.NullPointerException
at dao.DireccionDao.traerListaRubros(DireccionDao.java:128)
at prueba.prueba.main(prueba.java:12)
if anyone can help me with that i´m so grateful
thanks!
If you are mapping one Direccion to many Personas, this is a one-to-many mapping. This also means that the Persona has a many-to-one relationship with Direccion. You have a List<Persona> variable under the Direccion class. Now you need to have a Direccion class variable for the Persona class.
Here is an example of hibernate configuration with xml. http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example/
some times in Init-param and context-param you try to give same param-value that's why it is giving error.try to remove one.
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Sample Spring Maven Project</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml,
/WEB-INF/applicationContext-datasource.xml,
/WEB-INF/applicationContext-hibernate.xml</param-value>
</context-param>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--
I have removed this one.
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml,
/WEB-INF/applicationContext-datasource.xml,
/WEB-INF/applicationContext-hibernate.xml</param-value>
</init-param> -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

null pointer exception while creating session factory

I am getting null pointer exception at the line
SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ;
any suggestion what might be causing it ??
error log says this :
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:214)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1797)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1755)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
at com.hussi.model.Main.main(Main.java:15)
my Main class File :
package com.hussi.model;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args)
{
User user = new User();
user.setUsername("hussi");
user.setPassword("maria");
SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ;
Session session = sesionFactory.openSession();
Transaction tr = session.beginTransaction();
session.save(user);
session.flush();
session.close();
}
}
my model file
package com.hussi.model;
public class User
{
int user_id;
String username;
String password;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString()
{
return "username==>"+this.username+" : password==>"+this.password;
}
}
my user.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="com.hussi.model.User" table="users">
<id name="user_id" type="int" column="user_id">
<generator class="increment" />
</id>
<property name="username">
<column name="username"/>
</property>
<property name="password">
<column name="password"/>
</property>
</class>
</hibernate-mapping>
my hibernate configuration file : hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc.mysql://localhost:3306/my_hibernate_1</property>
<property name="connection.username">root</property>
<property name="connecttion.password">root</property>
<!-- Database connection settings -->
<property name="connection.pool_size">1</property>
<!-- MySql Dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
You have given wrong url
below is correct one
jdbc:mysql://localhost:3306/my_hibernate_1
Just replaced jdbc.mysql with jdbc:mysql
Try changing the hibernate config connection.url property to jdbc:myql

Categories

Resources