Mapping an java object to a database - java

I am tring to map a java object to database(i am using postgres). when i am runnig the java file (HibernateTest.java) it is showing lot of errors. i think all thing are correct. but i am doubtfull in my eclipse,bcoz it is not supporting xml ( i mean it is not showing color, it is not taking xml file as a know file ). i am a beginner so i cant understand them. plz suggest me.
hibernate.cfg.xml file
<?xml version='1.0' encoding='utf-8'?>
<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">org.postgresql.Driver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost:5432/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">hkm#1160</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQlDialect</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>
<!-- 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 resource="org.hibernate.hemant.dto.UDestails"/>
</session-factory>
</hibernate-configuration>
UserDetails.java file
package org.hibernate.hemant.dto;
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;
}
}
my main java file HibernateTest.java
package org.hemant.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.hemant.dto.UserDetails;
public class HibernateTest {
/**
* #param args
*/
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserID(1);
user.setUserName("First user");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.beginTransaction().commit();
}
}
There are the errors......
Apr 13, 2016 9:26:08 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
Apr 13, 2016 9:26:08 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Apr 13, 2016 9:26:08 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassistException in thread "main"
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 13 and column 63 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 org.hemant.hibernate.HibernateTest.main(HibernateTest.java:15)
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 13; columnNumber: 63; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Unknown Source)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
... 6 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 13; columnNumber: 63; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
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.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleStartElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(Unknown Source)
... 9 more

The cause of exception is an incorrect hibernate.cfg.xml file.
Please, use this structure
<!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>
...
<mapping class="org.hibernate.hemant.dto.UDestails" />
</session-factory>
</hibernate-configuration>
You incorrect specify a persistent class in hibernate.cfg.xml. You use a mapping with annotations so you need to map a class not a resource
<mapping class="org.hibernate.hemant.dto.UDestails" />
Please, don't forget to close a session and sessionFactory.

Related

Connection with MySQL database. Xml error Intellij

I'm trying to connect with my local MySQL database. When im trying to connect via session factory it throws following errror:
INFO: HHH000206: hibernate.properties not found
java.lang.ExceptionInInitializerError
at Main.<clinit>(Main.java:22)
Caused by: org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE hibernate.cfg.xml. Message: null
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:258)
at org.hibernate.cfg.Configuration.configure(Configuration.java:244)
at Main.<clinit>(Main.java:18)
Caused by: javax.xml.bind.JAXBException
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:241)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:477)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:656)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:599)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
... 6 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
at javax.xml.bind.ContextFinder.safeLoadClass(ContextFinder.java:594)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:239)
... 10 more
Exception in thread "main"
Process finished with exit code 1
My main class is generated with persistence mapping
hibernate.cfg.xml file:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<mapping class="entities.AddressEntity"/>
<mapping class="entities.AnimalEntity"/>
<mapping class="entities.OwnerEntity"/>
</session-factory>
</hibernate-configuration>
I generated classes and .xml file via persistence mapping option in intelliJ. Thanks in advance for a quick response.

Hibernate: no persistent classes found for query class but mapping is correct

This question has been asked many times, but I have not encountered a solution for my problem as on first sight everything seems right. It is a configuration problem when using this Hibernate setup:
hibernate-core: 5.2.11.Final
hibernate-jpa-2.1-api: 1.0.0.Final
hibernate-commons-annotations: 5.0.1.Final
When I try to execute a query I get a warning in the console that says no persistent classes found for query class but no error is thrown, and no data is retrieved from database although it should return over 30 entries.
09:56:58,203 INFO [org.hibernate.Version] (default task-46) HHH000412: Hibernate Core {5.2.11.Final}
09:56:58,206 INFO [org.hibernate.cfg.Environment] (default task-46) HHH000206: hibernate.properties not found
09:56:58,348 INFO [org.hibernate.annotations.common.Version] (default task-46) HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
09:56:58,397 WARN [org.hibernate.orm.connections.pooling] (default task-46) HHH10001002: Using Hibernate built-in connection pool (not for production use!)
09:56:58,398 INFO [org.hibernate.orm.connections.pooling] (default task-46) HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/db_motor?useSSL=false&autoReconnect=true]
09:56:58,398 INFO [org.hibernate.orm.connections.pooling] (default task-46) HHH10001001: Connection properties: {user=admin, password=****}
09:56:58,398 INFO [org.hibernate.orm.connections.pooling] (default task-46) HHH10001003: Autocommit mode: false
09:56:58,400 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (default task-46) HHH000115: Hibernate connection pool size: 10 (min=1)
09:56:58,647 INFO [org.hibernate.dialect.Dialect] (default task-46) HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
09:56:58,958 WARN [org.hibernate.hql.internal.QuerySplitter] (default task-46) HHH000183: no persistent classes found for query class: SELECT respuestas FROM mr.hibernate.beans.MR_RespuestasHBean respuestas
09:56:58,959 INFO [org.hibernate.hql.internal.QueryTranslatorFactoryInitiator] (default task-46) HHH000397: Using ASTQueryTranslatorFactory
It seems the warning about hibernate.properties not found is not of any influence if I interpret information found on this website correctly.
The 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 name="session_factory">
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.password">admin</property>
<property name="connection.pool_size">10</property> <!-- not for production -->
<property name="connection.url">jdbc:mysql://localhost:3306/db_motor?useSSL=false&autoReconnect=true</property>
<property name="connection.username">admin</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<mapping class="mr.hibernate.beans.MR_RespuestasHBean"/>
</session-factory>
</hibernate-configuration>
The mapped class:
package mr.hibernate.beans;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "t_respuestas")
public class MR_RespuestasHBean implements Serializable {
private static final long serialVersionUID = 3892055031093758454L;
#Id
#Column(name = "COD_RESPUESTA", nullable = false, length = 11)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long codigoRespuesta;
public Long getCodigoRespuesta() {
return codigoRespuesta;
}
public void setCodigoRespuesta(Long codigoRespuesta) {
this.codigoRespuesta = codigoRespuesta;
}
}
Table definition:
CREATE TABLE t_respuestas
(
COD_RESPUESTA int PRIMARY KEY NOT NULL
)
;
CREATE UNIQUE INDEX PRIMARY ON t_respuestas(COD_RESPUESTA)
;
The code used to get the query is this:
session = getSession(HibernateUtil.configurationFileMySql);
session.beginTransaction();
StringBuffer hql = new StringBuffer();
StringBuffer select = new StringBuffer();
select.append("SELECT respuestas");
StringBuffer from = new StringBuffer();
from.append(" FROM "+ MR_RespuestasHBean.class.getName() +" respuestas");
hql.append(select);
hql.append(from);
#SuppressWarnings("unchecked")
Query<MR_RespuestasHBean> query = session.createQuery(hql.toString());
listado = query.list();
If I change MR_RespuestasHBean.class.getName() by MR_RespuestasHBean.class.getSimpleName(), an error is thrown:
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: MR_RespuestasHBean is not mapped
Some information on the environment:
JBoss EAP7
JDK8
MySql connector 6.0.6
The Hibernate part is in an EJB3 project
However, when using this setup, everything works well (logically, session loading and query execution has to be different):
hibernate-core: 4.2.0.Final
hibernate-jpa-2.0-api: 1.0.1.Final
hibernate-commons-annotations: 4.0.1.Final
Any clues on what is causing the problem is very much appreciated.

hibernate 5 configuration for oracle11g in eclipse

I am trying to configure hibernate 5 to access oracle 11 g in eclipse.
hibernate.cfg.xml is as follows:
In following xml i have specified database credentials(url, username and password),dilect, mapping class, show_sql . I want to ask if I missed any important property.
<?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>.
-->
<!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">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#127.0.0.1:1521:orcl</property> -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#127.0.0.1:1521:XE</property>
<property name="connection.username">SYSTEM</property>
<property name="connection.password">motog</property>
<mapping class="com.demo.one.Hello"/>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.OracleDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<property name="cache.use_query_cache">true</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.use_structured_entries">true</property>
<property name="cache.region.factory_class">org.hibernate.cache.EhCacheRegionFactory</property>
<property name="net.sf.ehcache.configurationResourceName">/hibernate-config/ehcache.xml</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<mapping resource="hibernate-config/domain/Event.hbm.xml"/>
<mapping resource="hibernate-config/domain/Person.hbm.xml"/>
<mapping resource="hibernate-config/domain/PhoneNumber.hbm.xml"/>
<mapping resource="hibernate-config/domain/Account.hbm.xml"/>
<mapping resource="hibernate-config/domain/HolidayCalendar.hbm.xml"/>
<mapping resource="hibernate-config/domain/Item.hbm.xml"/>
</session-factory>
</hibernate-configuration>
[image specifies project structure and imported libraries][1]
Defined Hello class as Table name by using #Entity and userId as primary key by using #Id
Hello.java:
package com.demo.one;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Hello {
#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;
}
} // end of Hello.java
Following class tries to save instance of Hello in database.
OracleTest.java:
package com.demo.one;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class OracleTest {
public static void main(String[] args) {
Hello z = new Hello();
z.setUserId(2);
z.setUserName("ashish");
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(z);
session.getTransaction().commit();
}
} // End of OracleTest.java
I am trying to save Hello class's object in oracle 11g XE database(resides on my local machine) , OracleTest.java is written for that.
I am getting following errors.
Jan 17, 2016 6:08:01 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.7.Final}
Jan 17, 2016 6:08:01 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jan 17, 2016 6:08:01 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 -1 and column -1 in RESOURCE hibernate.cfg.xml. Message: cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://www.hibernate.org/xsd/orm/cfg":mapping, "http://www.hibernate.org/xsd/orm/cfg":class-cache, "http://www.hibernate.org/xsd/orm/cfg":collection-cache, "http://www.hibernate.org/xsd/orm/cfg":event, "http://www.hibernate.org/xsd/orm/cfg":listener}' is expected.
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.demo.one.OracleTest.main(OracleTest.java:13)
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://www.hibernate.org/xsd/orm/cfg":mapping, "http://www.hibernate.org/xsd/orm/cfg":class-cache, "http://www.hibernate.org/xsd/orm/cfg":collection-cache, "http://www.hibernate.org/xsd/orm/cfg":event, "http://www.hibernate.org/xsd/orm/cfg":listener}' is expected.]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(Unknown Source)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
... 6 more
Caused by: org.xml.sax.SAXParseException; cvc-complex-type.2.4.a: Invalid content was found starting with element 'property'. One of '{"http://www.hibernate.org/xsd/orm/cfg":mapping, "http://www.hibernate.org/xsd/orm/cfg":class-cache, "http://www.hibernate.org/xsd/orm/cfg":collection-cache, "http://www.hibernate.org/xsd/orm/cfg":event, "http://www.hibernate.org/xsd/orm/cfg":listener}' is expected.
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.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleStartElement(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(Unknown Source)
... 9 more
please guide me, its my first encounter with hibernate.
PS: please check attached image. link is at the bottom.
regards
ashish
[1]: http://i.stack.imgur.com/DBYxu.png
The error message tells you that it's not expecting a <property> element somewhere. Instead, it expects a <mapping> element, or a <class-cache> element, or...
And indeed, the DTD has the following definition:
<!ELEMENT session-factory (property*, mapping*, (class-cache|collection-cache)*, event*, listener*)>
This means that, under <session-factory>, you're supposed to have 0 or more <property> elements, then 0 or more <mapping> elements.
But your xml file has
<property name="connection.password">motog</property>
<mapping class="com.demo.one.Hello"/>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
So you have a <mapping>element in the middle of <property> elements. That is thus invalid.

Configuring tomcat, hibernate and mysql

I created a dynamic web project named HibernateSetUpTest2, jpa is marked as one of the project facets. I want to put this on a tomcat server in the future but right now I simply need to test if hibernate is working and it isn't.
I followed the MySQL DBCP Example on here (except for the jsp part):
https://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html
Now my xmls look like this:
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="unitName" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/TestDB</jta-data-source>
<class>entities.TestDataRow</class>
<properties>
<property name="hibernate.transaction.jta.platform"
value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<!-- andere properties hier definiƫren -->
<!-- geen properties definiƫren voor password, user, driver etc; want
we gebruiken datasource -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.connection.autocommit" value="true" />
</properties>
</persistence-unit>
</persistence>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>HibernateSetUpTest2</display-name>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
In the project explorer of eclipse it shows a separate folder named Servers and in it is the context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest"/>
</Context>
In my src folder I wrote a Test:
package tests;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import entities.TestDataRow;
public class Hibernate {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("unitName");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
TestDataRow t = em.find(TestDataRow.class, 1);
System.out.println(t.getFoo());
tx.commit();
em.close();
emf.close();
}
}
This uses the entity:
package entities;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="testdata")
public class TestDataRow {
#Id
private int id;
private String foo;
private int bar;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
public int getBar() {
return bar;
}
public void setBar(int bar) {
this.bar = bar;
}
}
When I run the test as a java application it throws errors:
Dec 14, 2015 3:34:31 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
name: unitName
...]
Dec 14, 2015 3:34:31 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.5.Final}
Dec 14, 2015 3:34:31 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 14, 2015 3:34:31 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Dec 14, 2015 3:34:31 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Exception in thread "main" javax.persistence.PersistenceException: Unable to build entity manager factory
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:66)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at tests.Hibernate.main(Hibernate.java:12)
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:770)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:797)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:58)
... 3 more
Caused by: org.hibernate.engine.jndi.JndiException: Error parsing JNDI name [jdbc/TestDB]
at org.hibernate.engine.jndi.internal.JndiServiceImpl.parseName(JndiServiceImpl.java:124)
at org.hibernate.engine.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:95)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:98)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:217)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.buildJdbcConnectionAccess(JdbcEnvironmentInitiator.java:145)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:66)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
... 14 more
Caused by: 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(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:350)
at javax.naming.InitialContext.getNameParser(InitialContext.java:505)
at org.hibernate.engine.jndi.internal.JndiServiceImpl.parseName(JndiServiceImpl.java:118)
... 24 more
What am I doing wrong?
Your code itself looks fine (can't tell for sure but nothing seems to be seriously wrong) but you have a huge issue with your test itself:
It is a standalone test.
What the errormessage is telling you:
javax.naming.NoInitialContextException: Need to specify class name in environment or system property
Basically means, that while attempting to lookup the JNDI variable (your DB resource definition) it had nowhere to "look". There is no context in your test. That is why it failed.
The standard ways of dealing with this kind of problem are:
either programmatically creating a context
or - just for the sake of the test - inserting a DB resource definition via simple autowiring, and not using JNDI at all.
Example and source for further ideas can be found here:
Setting up JNDI Datasource for uni testing
I think you need some initialisation or its a lack of configuration
jndi.java.naming.provider.url=jnp://localhost:1099/
jndi.java.naming.factory.url=org.jboss.naming:org.jnp.interfaces
jndi.java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory

WARN: SQL Error: 1064, SQLState: 42000

I have a problem with hibernate query.
UPDATE:
When I use this query it works like a charm:
public static List<Korisnik> UzmiSveKorisnike()
{
EntityManager em = Konekcija.getEmf().createEntityManager();
TypedQuery<Korisnik> q = em.createQuery("select k from Korisnik k where k.isActive = 1", Korisnik.class);
List<Korisnik> resultList = q.getResultList();
em.close();
return resultList;
}
But when I use one listed below, to select single result (like for login)...
I get this error: WARN: SQL Error: 1064, SQLState: 42000
I have tried variety of ways to implement this query, but without success. I will list them at the end of the post.
This is the code:
public static Korisnik ProvjeraKorisnickihPodataka(String kIme, String kLozinka)
{
EntityManager em = Konekcija.getEmf().createEntityManager();
{
TypedQuery<Korisnik> q = em.createQuery("select k from Korisnik k where k.isActive = 1 AND k.korisnickoIme=:ime AND k.lozinka =:lozinka", Korisnik.class);
q.setParameter("ime", kIme);
q.setParameter("lozinka", kLozinka);
Korisnik provjeren = q.getSingleResult();
em.close();
return provjeren;
Even if I replace :ime and :lozinka with actual data like "k.korisnickoIme='msbtest' and k.lozinka = 'msbtest'" I get the same error.
Your help is appreciated.
Thank you!
Complete stack:
Hibernate: select TOP(?) korisnik0_.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, korisnik0_.ime as ime11_, korisnik0_.isActive as isActive11_, korisnik0_.kontakt as kontakt11_, korisnik0_.korisnickoIme as korisnic5_11_, korisnik0_.lozinka as lozinka11_, korisnik0_.prezime as prezime11_, korisnik0_.rola_RolaID as rola9_11_ from Korisnik korisnik0_ where korisnik0_.isActive=1 and korisnik0_.korisnickoIme=? and korisnik0_.lozinka=?
Jul 05, 2013 11:45:22 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
Jul 05, 2013 11:45:22 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:318)
at Servis.LoginServis.ProvjeraKorisnickihPodataka(LoginServis.java:35)
at UI.LogInFrm.do_btnPrijava_widgetSelected(LogInFrm.java:173)
at UI.LogInFrm$1.widgetSelected(LogInFrm.java:121)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at UI.LogInFrm.main(LogInFrm.java:44)
Caused by: org.hibernate.exception.SQLGrammarException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy10.executeQuery(Unknown Source)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1926)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1727)
at org.hibernate.loader.Loader.doQuery(Loader.java:852)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:293)
at org.hibernate.loader.Loader.doList(Loader.java:2411)
at org.hibernate.loader.Loader.doList(Loader.java:2397)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2227)
at org.hibernate.loader.Loader.list(Loader.java:2222)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1247)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:285)
... 9 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
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 com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 25 more
mapping goes like this:
/**
** Class Korisnik
**/
#Entity
public class Korisnik implements Serializable {
//Fields
#Id
#GeneratedValue
private Integer KorisnikID;
private String ime;
private String prezime;
private String kontakt;
private String korisnickoIme;
private String lozinka;
private Boolean isActive;
#JoinColumn(nullable = false)
#ManyToOne
private Agencija agencija;
#JoinColumn(nullable = false)
#ManyToOne
private Rola rola;
and getters and setters go...
OK, my persistence.xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="MojaOznaka1" transaction-type="RESOURCE_LOCAL">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<!-- Podaci o bazi podataka -->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://xxxxxxxxx.xxxxxxxxx.xxx/xxxxxxxxx/" />
<property name="javax.persistence.jdbc.user" value="xxxxxx" />
<property name="javax.persistence.jdbc.password" value="xxxxxx" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<!-- hiberante dialect -->
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2008Dialect" />
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size" value="1" />
<!-- Ispis SQL koda u konzolu -->
<property name="hibernate.show_sql" value="true" />
<!-- formatiranje SQL koda ispisanog u konzolni prozor -->
<property name="hibernate.format_sql" value="false" />
<!-- Vrijednost "update" kreira tabele ako nepostoje -->
<!-- <property name="hibernate.hbm2ddl.auto" value="update" /> -->
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class" value="thread" />
<!-- Disable the second-level cache -->
<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
<!-- automatsko prepoznavanje JPA klasa -->
<property name="hibernate.archive.autodetection" value="class, hbm" />
</properties>
</persistence-unit>
</persistence>
OK, now what???
The query output you give suggests you told Hibernate to generate SQL for a MS-SQL Server (using TOP(1) to fetch the topmost row).
Since you're using a mysql database as a backend, that won't work. Try adding
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
to your persistence.xml or wherever you configure JPA.
As #Secko mentions in the comment, omitting the dialect altogether might even select a better (more specific) one.
This error usually indicates some mapping error. Are all fields used in the where are actually fields of the "Korisnik" class? HQL uses the field names and not the column names from the database.

Categories