How to connect Hibernate with MySQL - java

I want to connect Hibernate with MySQL. I tried all methods, but I'm still getting this error. I'm using Hibernate the version.
avr. 19, 2018 1:55:21 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.16.Final}
avr. 19, 2018 1:55:21 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
avr. 19, 2018 1:55:22 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
avr. 19, 2018 1:55:24 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
avr. 19, 2018 1:55:24 PM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator initiateService
WARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
avr. 19, 2018 1:55:24 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : The application must supply JDBC connections
Exception in thread "main" 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:271)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
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:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
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.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at TestHibernate1.main(TestHibernate1.java:14)
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
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:259)
===========================================================================
=> this is my hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/bd_per</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="Personnes.hbm.xml"/>
</session-factory>
</hibernate-configuration>
=> this is my hibernate-mapping
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping"><hibernate-mapping>
<class name="Personnes" table="personnes">
<id name="idPersonne" type="int" column="idpersonne">
<generator class="native"/>
</id>
<property name="nomPersonne" type="string" not-null="true" />
<property name="prenomPersonne" type="string" not-null="true" />
</class>
</hibernate-mapping>
=> finaly my classe Personnes
public class Personnes {
private Integer idPersonne;
private String nomPersonne;
private String prenomPersonne;
public Personnes(String nomPersonne, String prenomPersonne) {
this.nomPersonne = nomPersonne;
this.prenomPersonne = prenomPersonne;
}
public Personnes() {
}
public Integer getIdPersonne() {
return idPersonne;
}
public String getNomPersonne() {
return nomPersonne;
}
public String getPrenomPersonne() {
return prenomPersonne;
}
public void setIdPersonne(Integer integer) {
idPersonne = integer;
}
And,thanks for responding as quickly as possible.
public void setPrenomPersonne(String string) {
prenomPersonne = string;
}
public void setNomPersonne(String string) {
// TODO Auto-generated method stub
}
}

At least you need to use dialect from this package https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/dialect/package-summary.html not from net.sf.hibernate.dialect. For example org.hibernate.dialect.MySQL5Dialect
The package you use was in old hibernate version.
And why do you use xml-style definition?

The proper hibernate dialect needs to be selected depending on the version of MySQL. I faced similar issue and resolution was very simple of using InnoDB dialect version of MySQL.
You can refer the proper dialect from package: org.hibernate.dialect
Referece : Link

Related

Cannot create JDBC driver of class 'oracle.jdbc.driver.OracleDriver' for connect URL 'jdbc:orcale:thin:#localhost:1521:xe'

I am writing a program based on CURD operation based on Spring-orm module.
//dao class
//StudentDAO.java
package com.nt.dao;
import com.nt.domains.StudentInfo;
public interface StudentDAO {
public StudentInfo getStudentInfo(int sid);
}
//StudentInfo.java
package com.nt.dao;
import org.springframework.orm.hibernate5.HibernateTemplate;
import com.nt.domains.StudentInfo;
public class StudnetInfoImpl implements StudentDAO {
//bean
private HibernateTemplate htemplate;
public void setHtemplate(HibernateTemplate htemplate) {
this.htemplate = htemplate;
}
#Override
public StudentInfo getStudentInfo(int sid) {
StudentInfo studentInfo=null;
studentInfo=(StudentInfo)htemplate.save(sid);
return studentInfo;
}
}
//service class
//studentservice.java
package com.nt.service;
import com.nt.domains.StudentInfo;
public interface StudentService {
public StudentInfo getStudentDetails(int sid);
}
//studentserviceimpl.java
package com.nt.service;
import com.nt.dao.StudentDAO;
import com.nt.domains.StudentInfo;
public class StudentServiceImpl implements StudentService {
//beans
private StudentDAO dao;
//setters
public void setDao(StudentDAO dao) {
this.dao = dao;
}
//override method
#Override
public StudentInfo getStudentDetails(int sid) {
StudentInfo info=null;
info=dao.getStudentInfo(sid);
return info;
}
Spring configuration file
//service-bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="service" class="com.nt.service.StudentServiceImpl">
<property name="dao" ref="dao"></property>
</bean>
</bean
//persistance-bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dbcp" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:orcale:thin:#localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="jinibini123"/>
</bean>
<bean id="sesfact" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dbcp"/>
<property name="annotatedClasses">
<list>
<value>com.nt.domains.StudentInfo</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sesfact"/>
</bean>
<bean id="dao" class="com.nt.dao.StudnetInfoImpl">
<property name="htemplate" ref="template"/>
</bean>
</beans>
//applicationcontext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="persistance-beans.xml"/>
<import resource="service-beans.xml"/>
</beans>
//clientapplicatrion
//CURDTet.java
package com.nt.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.nt.service.StudentService;
public class CURDTest {
public static void main(String[] args) {
//create IOC
ApplicationContext ctx=null;
StudentService service=null;
ctx=new ClassPathXmlApplicationContext("com/nt/cfgs/applicationcontext.xml");
service=ctx.getBean("service",StudentService.class);
//invoke methods
System.out.println("101 table records:"+service.getStudentDetails(101));
//close IOC
((AbstractApplicationContext) ctx).close();
}
}
When I'm trying to run this program on Tomcat 8.0 server I am getting the following exception. Can you please help me how to proceed further...
Sep 01, 2017 12:17:47 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#6b179d: startup date [Fri Sep 01 12:17:47 IST 2017]; root of context hierarchy
Sep 01, 2017 12:17:47 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/nt/cfgs/applicationcontext.xml]
Sep 01, 2017 12:17:48 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/nt/cfgs/persistance-beans.xml]
Sep 01, 2017 12:17:48 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/nt/cfgs/service-beans.xml]
Sep 01, 2017 12:17:48 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
Sep 01, 2017 12:17:48 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 01, 2017 12:17:48 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Sep 01, 2017 12:17:48 PM org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator initiateService
WARN: HHH000342: Could not obtain connection to query metadata : Cannot create JDBC driver of class 'oracle.jdbc.driver.OracleDriver' for connect URL 'jdbc:orcale:thin:#localhost:1521:xe'
Sep 01, 2017 12:17:48 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Sep 01, 2017 12:17:48 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl makeLobCreatorBuilder
INFO: HHH000422: Disabling contextual LOB creation as connection was null
Sep 01, 2017 12:17:49 PM org.hibernate.hql.spi.id.IdTableHelper executeIdTableCreationStatements
ERROR: Unable obtain JDBC Connection
org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class 'oracle.jdbc.driver.OracleDriver' for connect URL 'jdbc:orcale:thin:#localhost:1521:xe'
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1150)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.SessionFactoryImpl$1.obtainConnection(SessionFactoryImpl.java:419)
at org.hibernate.hql.spi.id.IdTableHelper.executeIdTableCreationStatements(IdTableHelper.java:67)
at org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:125)
at org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:42)
at org.hibernate.hql.spi.id.AbstractMultiTableBulkIdStrategyImpl.prepare(AbstractMultiTableBulkIdStrategyImpl.java:88)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:302)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:511)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:495)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:742)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.nt.test.CURDTest.main(CURDTest.java:15)
Caused by: java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getDriver(Unknown Source)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1143)
... 27 more
Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
at org.springframework.orm.hibernate5.HibernateTemplate.checkWriteOperationAllowed(HibernateTemplate.java:1165)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:643)
at org.springframework.orm.hibernate5.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:640)
at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:359)
at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:326)
at org.springframework.orm.hibernate5.HibernateTemplate.save(HibernateTemplate.java:640)
at com.nt.dao.StudnetInfoImpl.getStudentInfo(StudnetInfoImpl.java:22)
at com.nt.service.StudentServiceImpl.getStudentDetails(StudentServiceImpl.java:19)
at com.nt.test.CURDTest.main(CURDTest.java:18)

Hibernate ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml] IntelliJ

I have a problem with my hibernate.cfg.xml in IntelliJ IDE.
Here is my hibernate config 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>
<!-- Database connection settings -->
<property name="connection.driver:class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost/HIndex</property>
<property name="hibernate.connection.username">index_user</property>
<property name="hibernate.connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</property>
<!-- Assume test is the database name -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="HIndexSaar.HIndex.Person"/>
<mapping class="HIndexSaar.HIndex.University"/>
<mapping class="HIndexSaar.HIndex.Publication"/>
</session-factory>
</hibernate-configuration>
And this is my application class:
package HIndexSaar.HIndex;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateManager {
private static SessionFactory factory;
public HibernateManager(){
//
//* Setup the configuration.
//
Configuration config = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Person.class) .addAnnotatedClass(University.class).addAnnotatedClass(Publication.class);
factory = config.buildSessionFactory();
}
I get an error by running the following code:
package HIndexSaar.HIndex;
public class AppHibernate {
public static void main(String[] args){
HibernateManager mng = new HibernateManager();
[...]
}
}
So something seems to be broken in building the SessionFactory in the HibernateManager. I get the error
Could not locate cfg.xml resource
and the following stacktrace:
Feb 27, 2016 10:26:03 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.7.Final}
Feb 27, 2016 10:26:03 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 27, 2016 10:26:03 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53)
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 HIndexSaar.HIndex.HibernateManager.<init>(HibernateManager.java:18)
at HIndexSaar.HIndex.AppHibernate.main(AppHibernate.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
I already have placed the hibernate.cfg.xml file under /src/main/java/resources but obviously something goes still wrong.
Does somebody have an idea what could be the mistake I made? Surprisingly, the same code runs in Eclipse without error, so what could be the problem of IntelliJ? I use the same SDK/JDK, namely jdk 1.7.
If your are using intellij then try to create new module with hibernate framework support then paste this same code and execute it.
This might be path difference in clipse and intellij

Error running Hibernate project in IntelliJ IDEA 15.0.3

I have hibernate project structure like this
My hibernate.cfg.xml is
<?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:sqlserver://localhost:1433;databaseName=WSMS</property>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<mapping class="test.IssuesEntity"/>
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>
My main class is
public class Main {
public static void main(String[] args) throws Exception {
/// System.out.print("jajaja");
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();
//creating session object
Session session=factory.openSession();
//creating transaction object
Transaction t=session.beginTransaction();
IssuesEntity e1=new IssuesEntity();
// e1.setId(115);
// e1.setFirstName("sonoo");
// e1.setLastName("jaiswal");
e1.setIssueName("akash");
session.persist(e1);//persisting the object
t.commit();//transaction is commited
session.close();
System.out.println("successfully saved");
}
}
But whenever i run project it shows following error
Feb 26, 2016 10:02:59 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Feb 26, 2016 10:03:00 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.2.Final}
Feb 26, 2016 10:03:00 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 26, 2016 10:03:00 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
I have followed intellij instruction but i can not find any solution. Please help
It is not an error. It is just an information that you don't have hibernate.properties file in the class path. You have properties in the hibernate.cfg.xml, it is ok too. But you need to specify hibernate.dialect, hibernate.connection.username and hibernate.connection.password.
And if you don't have tables in the database you need this too
<property name="hbm2ddl.auto">update</property>

Hibernate Configuration Loading Error

I am trying to create a simple hibernate project, but I am getting error while reading hibernate.cfg.xml file, dont know what the issue is, below is the code and error trace. Please help.
Here is my hibernate.cfg.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>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/EPS</property>
<property name="hibernate.connection.username">haris</property>
<property name="hibernate.connection.password">ihatecookies</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="hibernate.connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<!-- Drop or re-create database -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping class="com.secure.eps.model.User"/>
</session-factory>
</hibernate-configuration>
Here is my main class:
package com.secure.eps.controller;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.secure.eps.model.User;
public class HibernateUtil {
public static void main(String args[]){
User user = new User();
user.setUsername("RoojiPooji");
user.setPassword("ihatecookies");
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.configure().buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
Here is error stack:
Sep 24, 2014 9:37:41 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
Sep 24, 2014 9:37:41 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.6.Final}
Sep 24, 2014 9:37:41 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5}
Sep 24, 2014 9:37:41 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Sep 24, 2014 9:37:41 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
Sep 24, 2014 9:37:41 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2163)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2075)
at com.secure.eps.controller.HibernateUtil.main(HibernateUtil.java:19)
Caused by: org.dom4j.DocumentException: null Nested exception: null
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2155)
... 2 more
I believe it is an issue with this line in your xml configuration.
<!-- Mapping files -->
<mapping class="com.secure.eps.model.User"/>
Refer to hibernate docs: http://www.tutorialspoint.com/hibernate/hibernate_mapping_files.htm.

How to create a JNDI using Eclipse and Tomcat for a Dynamic Web Project without web.xml

I would like to know how to create a JNDI entry for a MySQL database using Eclipse Kepler and Tomcat 7 (Is there a plugin for Eclipse?).
When I created the Dynamic Web Project using Eclipse, I did NOT checked the "Generate web.xml deployment descriptor", so, I do not have a web.xml file in my project.
The JDNI resource definition is declared in Tomcat's <Context> element in context.xml 1, not your new application's web.xml. So whether it's generated or not, it doesn't actually matter.
<Context>
<Resource name="jdbc/YourDB" auth="Container"
type="javax.sql.DataSource"
username="username" password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://dbserver:dbport/actualDbname"/>
</Context>
If you had web.xml in your application, you will need an entry like this to refer to the datasource mentioned above:
<resource-ref>
<res-ref-name>jdbc/YourDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Since you opted not to have web.xml, you can use annotations:
#Resource(lookup = "java:comp/env/jdbc/YourDB")
private DataSource dataSource;
1 There are multiple ways to define the Context, refer to Tomcat's definition on Defining a Context.
When I posted the question, I forgot to say that I'm using Hibernate and to include the files.
The hibernate.cfg.xml is:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE
hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.datasource">java:comp/env/jdbc/ExemplosWeb</property>
<property name="hibernate.connection.username">TheUsername</property>
<property name="hibernate.connection.password">ThePassword</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- One to One Unidirecional -->
<mapping class="relacionamentoHibernate.bean.PaiOneToOneUnidirecional"/>
<mapping class="relacionamentoHibernate.bean.FilhoOneToOneUnidirecional"/>
</session-factory>
There is an Hibernate util class:
package hibernateUtil;
import javax.annotation.Resource;
import org.hibernate.*;
import org.hibernate.cfg.*;
#Resource(lookup="java:comp/env/jdbc/exemplosweb")
#SuppressWarnings("deprecation")
public class HibernateUtil
{
private static final SessionFactory sessionFactory;
static
{
try
{
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
}
catch (HibernateException e)
{
// Make sure you log the exception, as it might be swallowed
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
catch (NoClassDefFoundError e)
{
e.printStackTrace();
throw new NoClassDefFoundError("static HibernateUtil");
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
and I got this exception:
Fev 26, 2014 7:02:46 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Fev 26, 2014 7:02:46 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.4.Final}
Fev 26, 2014 7:02:46 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Fev 26, 2014 7:02:46 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Fev 26, 2014 7:02:46 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Fev 26, 2014 7:02:46 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Fev 26, 2014 7:02:46 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!
Fev 26, 2014 7:02:46 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
org.hibernate.service.jndi.JndiException: Unable to lookup JNDI name [java:comp/env/jdbc/ExemplosWeb]
at org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:68)
at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:116)
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)

Categories

Resources