I am trying to do a simple hibernate program. I am following the steps given in this tutorial.
The Error that I am getting is
org.hibernate.MappingNotFoundException: resource: org.manu.dtd.UserDetails not found
at org.hibernate.cfg.Configuration.addResource(Configuration.java:799)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2344)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2310)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2290)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2243)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2158)
at org.manu.dtd.TestHibernate.main(TestHibernate.java:16)
Here is my folder structure
My persitence class with annotations is
package org.manu.dtd;
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 hibernate.cfg.xml file is
<?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">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="connection.username">user</property>
<property name="connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.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.manu.dtd.UserDetails"/>
</session-factory>
</hibernate-configuration>
And finally my main program is
package org.manu.dtd;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class TestHibernate {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(23);
user.setUserName("Renu");
System.out.println("setting values complete");
try {
SessionFactory sF = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sF.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
catch (HibernateException he) {
he.printStackTrace();
}
}
}
Can anyone please help me out to resolve this issue.
Well it looks it can be fixed even easier. You should use <mapping class=..> instead of <mapping resource=..> as resources is for mapping other xml files describing entities and such. Here is small example from the offical tutorials
Provide fully qualified name for hibernate configuration mapping file,
SessionFactory sF = new Configuration().
configure("/org/manu/dtd/hibernate.cfg.xml").buildSessionFactory();
Related
I'm new to hibernate and am trying to code something. I'm getting an stuck with an error ( Failed to create sessionFactory object.java.lang.NullPointerException )
Some help will be much appreciated.
hibernate.cfg.xml file :
<?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</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521/orclpdb1</property>
<property name="connection.username">oracle</property>
<property name="connection.password">admin</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.OracleDialect</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 class="ProjectHib.dto.Client"/>
</session-factory>
</hibernate-configuration>
Client.hbm.xml file :
<?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 = "Client" table = "Client">
<meta attribute = "class-description">
This class contains the employee detail.
</meta>
<id name = "ClientID" type = "int" column = "id">
<generator class="native"/>
</id>
<property name = "name" column = "name" type = "string"/>
</hibernate-mapping>
And then the Client.java file :
package ProjectHib.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Client {
#Id
private int ClientID;
private String name;
public Client() {}
public Client(int clientID, String name) {
ClientID = clientID;
this.name = name;
}
public int getClientID() {
return ClientID;
}
public void setClientID(int clientID) {
ClientID = clientID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Finally, the Hibernate test file :
package ProjectHib.dto;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class TestHibernate {
private static SessionFactory factory;
public static void main(String[] args) {
Client C1 = new Client();
C1.setClientID(0);
C1.setName("fat7i 1");
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
session.beginTransaction();
session.save(C1);
session.getTransaction().commit();
}
}
Edit : I was following a tutorial.. the purpose of this code is to save ( persist ) the object ( Clien C1 ) in a Oracle database ( I dont know if this clarifies things a bit )
Try inserting "oracle.jdbc.driver.OracleDriver" as your 'connection.driver_class' instead of 'oracle.jdbc.driver'.
This only works for JDK-compliant versions of Java.
I am trying to write my first hibernate annotation application and below are the things that i did
package org.hibernate.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class Employee {
#Id
#GeneratedValue
Integer id;
#Column(name="Employee_Name")
String userName;
#Column(name="Address")
String age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
/**
* Hi this is to test java commenting
* #return
*/
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Hibernate.config.xml
<?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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">$Ailaja12</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sessions</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<!-- <property name="show_sql">true</property> -->
<!-- <mapping resource="org/hibernate/pojo/Employee.xml"></mapping> -->
<mapping class="org.hibernate.pojo.Employee"/>
<mapping resource="org/hibernate/pojo/Item.xml"></mapping>
</session-factory>
</hibernate-configuration>
Client
package org.hibernate.client;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.pojo.Employee;
public class Client {
/**
* #param args
*/
public static void main(String[] args) {
//Starting hibernate environment in your application
Configuration conf = new Configuration();
//2 Loading hibernate configuration file
conf.configure("hibernate.cfg.xml");
SessionFactory factory=new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
//SessionFactory factory = conf.buildSessionFactory();
Session session = factory.getCurrentSession();
Employee ee = new Employee();
ee.setUserName("Kranthi");
//ee.setId(123);
ee.setAge("Dallas");
Transaction tx = session.beginTransaction();
session.save(ee);
tx.commit();
session.close();
factory.close();
}
}
I am getting below exception
Exception in thread "main" org.hibernate.MappingException: An AnnotationConfiguration instance is required to use
I tried by googling but none of them has worked
and below are the list of jars that i have used
antlr_2.7.6.jar
asm-3.3.1.jar
cglib-2.2.2.jar
domj-1.3.jar
ehcache.jar
hibernate-3.2.jar
javax.persistence.jar
jta.jar
mysql-connector.jar
commonlogging.jar
Add below jar to your class path: hibernate-annotations.3.3.0.GA.jar or add below dependency to your pom file,if you are using maven project
<dependency>
<groupId>hibernate-annotations</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.0.GA</version>
</dependency>
Need your insight, look forward to your succor.
This is the main method, trying to persist data into db with hibernate.
package com.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.dto.Employee;
public class HibernateTest {
public static void main(String[] args) {
Employee emp = new Employee();
System.out.println("abc");
emp.setFirstName("John");
emp.setLastName("More");
emp.setSalary(999999972);
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(emp);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
This is the model class, viz. Employee
package com.hibernate.dto;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Employee {
#Id
private int id;
private String firstName;
private String lastName;
private int salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
Here's hibernate.cfg.xml.
<?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">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/empdb</property>
<property name="connection.username">root</property>
<property name="connection.password">***</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>
<!-- 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">update</property>
<mapping class="com.hibernate.dto.Employee"/>
</session-factory>
</hibernate-configuration>
Jars which I've included listed as:
D:\hibernate-release-5.1.0.Final\lib\required\antlr-2.7.7.jar
D:\hibernate-release-5.1.0.Final\lib\required\classmate-1.3.0.jar
D:\hibernate-release-5.1.0.Final\lib\required\dom4j-1.6.1.jar
D:\hibernate-release-5.1.0.Final\lib\required\geronimo-jta_1.1_spec-1.1.1.jar
D:\hibernate-release-5.1.0.Final\lib\required\hibernate-commons-annotations-5.0.1.Final.jar
D:\hibernate-release-5.1.0.Final\lib\required\hibernate-core-5.1.0.Final.jar
D:\hibernate-release-5.1.0.Final\lib\required\hibernate-jpa-2.1-api-1.0.0.Final.jar
D:\hibernate-release-5.1.0.Final\lib\required\jandex-2.0.0.Final.jar
D:\hibernate-release-5.1.0.Final\lib\required\javassist-3.20.0-GA.jar
D:\hibernate-release-5.1.0.Final\lib\required\jboss-logging-3.3.0.Final.jar
D:\hibernate-release-5.1.0.Final\lib\jpa\hibernate-entitymanager-5.1.0.Final.jar
D:\hibernate-release-5.1.0.Final\lib\java8\hibernate-java8-5.1.0.Final.jar
C:\Users\arpit_pipersaniya\Downloads\javassist-3.12.0.GA.jar
C:\Users\arpit_pipersaniya\Downloads\mysql-connector-java-5.1.18.jar
When I run this java application, nothing happens and hence no desired result.
By tweaking configuration file, now it works file without any glitch.
This is how hibernate.cfg.xml looks like, now:
<?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>
*<!-- <?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">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/empdb</property>
<property name="connection.username">root</property>
<property name="connection.password">root2</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>
<!-- 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">update</property>
<mapping class="com.hibernate.dto.Employee"/>
</session-factory>
</hibernate-configuration>
I'm just starting with hibernate and I have a simple configuration that gives me this error: "relation "userdetails" does not exist" when I try to first save the only class I have.
my hibernate.gfg.xml file:
<!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.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">XXXX</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernatedb</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>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hdm2ddl.auto">create</property>
<mapping class="hibernate.project.UserDetails"/>
</session-factory>
</hibernate-configuration>
my only model class:
#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:
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("First User");
Configuration config = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
any ideas? I've found similar questions but didn't help. thanks!
The create property is incorrect : Use hbm2ddl instead of hdm2ddl
<property name="hibernate.hbm2ddl.auto">create</property>
OR
<property name="hbm2ddl.auto">create</property>
and not
hdm2ddl.auto
Seems to be typo at your end.
when i execute my Main class i get this execution
cant figure out the issue point
the error comes in the line
Transaction tr = session.beginTransaction();
error stack says :
ERROR: Access denied for user 'root'#'localhost' (using password: NO)
error===>org.hibernate.exception.GenericJDBCException: Could not open connection
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.setUser_id(1);
user.setUsername("hussi");
user.setPassword("maria");
SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ;
Session session = sesionFactory.openSession();
try{
Transaction tr = session.beginTransaction();
session.save(user);
}
catch(Exception e)
{
System.out.println("error===>"+e);
}
finally
{
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>
I believe you need to reset your database password. Follow this link to do the same:
http://dev.mysql.com/doc/refman/5.1/en/resetting-permissions.html
or the user priviliges are not correct. Follow this to set priviliges:
http://dev.mysql.com/doc/refman/5.1/en/default-privileges.html