Exception in Hibernate Configuration [duplicate] - java

This question already has answers here:
TNS-12505: TNS:listener does not currently know of SID given in connect descriptor
(17 answers)
Closed 5 years ago.
I am very new to Spring, Hibernate. while working on hibernate I am facing the following problem. I also searched related tags on stackoverflow, but couldn't found any relevant post that solved my issues.
Student.java File
package hibernatepractise;
public class Student {
private long id;
private String name;
private String degree;
private String phone;
public Student() {
super();
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getDegree() {
return degree;
}
public String getPhone() {
return phone;
}
public void setId(long String) {
id = String;
}
public void setName(String string) {
name = string;
}
public void setDegree(String string) {
degree = string;
}
public void setPhone(String string) {
phone = string;
}
public String toString() {
return name;
}
}
AddStudent.java File
package hibernatepractise;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import hibernatepractise.Student;
public class AddStudent {
private static SessionFactory sessionFactory;
public static void main(String args[]) throws Exception {
// begin if
// A
String name = "Jayesh Vyas";
String degree = "B.tech Completed";
String phone = "9421345678";
System.out.println("Name: " + name);
System.out.println("Degree: " + degree);
System.out.println("Phone: " + phone);
if ((name.equals("") || degree.equals("") || phone.equals(""))) {
System.out.println("All informations are Required");
} else {
try {// begin try
sessionFactory = new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory();
// sessionFactory1 = new
// Configuration().configure("com\\xml\\student1.cfg.xml").buildSessionFactory();
} catch (Exception e) {
System.out.println("mathan");
System.out.println(e.getMessage());
System.err.println("Initial SessionFactory creation failed."+ e);
}
Session s = sessionFactory.openSession();
// Session s1 =sessionFactory1.openSession();
// Transaction tx1= s1.beginTransaction();
Transaction tx = s.beginTransaction();
Student stu = new Student();
stu.setName(name);
stu.setDegree(degree);
stu.setPhone(phone);
s.save(stu);
tx.commit();
System.out.println("Added to oracle Database");
if (s != null)
s.close();
// Student1 stu1=new Student1();
// stu1.setName(name1);
// s1.save(stu1);
// tx1.commit();
// System.out.println("Added to mysql Database");
// if (s1 != null)
// s1.close();
}
// }// end of if A
}// end of method
}// end of class
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="studentFactory">
<property name="connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="connection.url">
jdbc:oracle:thin:#localhost:1521:test
</property>
<property name="connection.username">
system
</property>
<property name="connection.password">
manager
</property>
<property name="connection.pool_size">5</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.OracleDialect
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Student.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="hibernatepractise.Student" table="studentOracle1">
<id name="id" type="long" column="ID">
<generator class="increment" />
</id>
<property name="name" column="name" not-null="true" />
<property name="degree" column="degree" />
<property name="phone" column="phone" />
</class>
</hibernate-mapping>
I am facing the following errors in my code
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at hibernatepractise.AddStudent.main(AddStudent.java:42)
Caused by: java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:480)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:413)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
... 5 more
Caused by: oracle.net.ns.NetException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:361)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:966)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:292)
... 13 more
I know that there is a silly mistake in my code but I am not able to find out as I am new to hibernate so that's why i request you to please help me to get out from this problem.
I shall be highly thankful to you for this.
Thanks in Advance.

I believe the error lies in this line:
jdbc:oracle:thin:#localhost:1521:test. I think it should be
jdbc:oracle:thin:#localhost:1521/test
A / instead of a :

Related

Got Exception in thread "main" org.hibernate.HibernateException: hibernate.cgf.xml not found while running hibernate application

My Hibernate Application needs to retrieve the data stored in MySQL database.But i was successful in saving data into DB, but failed in retrieving.
Error Log
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.HibernateException: hibernate.cgf.xml not found
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:173)
at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:2035)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2016)
at mypack.DataInsertion.getInfo(DataInsertion.java:39)
at mypack.DataInsertion.main(DataInsertion.java:12)
hibernate.cfg.xml (Configuration file)
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibdb</property>
<property name="connection.user">root</property>
<property name="connection.password">admin</property>
<!-- Related to the connection END -->
<!-- Related to the hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Related to the hibernate properties END -->
<!-- List of XML mapping files -->
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
user.hbm.xml (Mapping file)
<?xml version="1.0"?> <!-- Mapping File to POJO Class -->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="mypack.DataProvider" table="user_info">
<id name="user_id" column="id">
<generator class="assigned"/>
</id>
<property name="user_name" column = "name" />
<property name="user_address" column = "address" />
</class>
</hibernate-mapping>
DataProvider.java (POJO Class)
package mypack; //POJO Class
public class DataProvider {
private int user_id;
private String user_name;
private String user_address;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
}
DataInsertion.java (Implementation Logic)
package mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DataInsertion {
public static void main(String[] args) {
//new DataInsertion().insertInfo();
new DataInsertion().getInfo();
}
public void insertInfo()
{
Configuration con = new Configuration(); //interation with hib
con.configure("hibernate.cfg.xml"); //registering to xml
SessionFactory SF = con.buildSessionFactory(); //creating session
Session session = SF.openSession(); //opening new session
DataProvider provider = new DataProvider();
provider.setUser_id(1);
provider.setUser_name("Goutham");
provider.setUser_address("Hunsur");
Transaction TR = session.beginTransaction();
session.save(provider);
System.out.println("Object saved successfully");
TR.commit(); //saving transaction
session.close();
SF.close();
}
public void getInfo()
{
Configuration con = new Configuration();
con.configure("hibernate.cgf.xml");
SessionFactory SF = con.buildSessionFactory();
Session session = SF.openSession();
Object obj = session.load(DataProvider.class,new Integer(1)); //We are binding data into obj from DataProvider class
DataProvider dp = (DataProvider) obj; //Typecasting into DataProvider
System.out.println("Name:"+dp.getUser_name());
System.out.println("Address:"+dp.getUser_address());
session.close();
SF.close();
}
}
Please Advise me,
Thanks.
you have wrong file name with typo hibernate.cgf.xml should be hibernate.cfg.xml
You have given wrong name hibernate.cgf.xml in getInfo method. That is why you are facing issue

Unable to Load Mapper Class in Hibernate

I'm very new to Hibernate. Followed by a youtube tutorial, I created a hibernate program but getting an error. Please find the Class and the error below. Solution for this will be highly grateful.
Error:
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Oct 29, 2016 4:36:53 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Oct 29, 2016 4:36:53 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Exception in thread "main" org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [Emp.hbm.xml]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:229)
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.<init>(AnnotationMetadataSourceProcessorImpl.java:104)
Main Function()
public static void main( String[ ] args ) throws ParseException {
Configuration cfg = new Configuration();
cfg.configure("Hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Transaction tx = s.beginTransaction();
String name2 = "yahoo";
LoginRegister lr = new LoginRegister();
lr.set_username(name2.toLowerCase()+"_user");
lr.set_password(name2.toLowerCase()+"_pass");
lr.set_last_update(new java.sql.Date(new SimpleDateFormat("yyyyMMdd").parse("20110210").getTime()));
s.save(lr);
s.flush();
tx.commit();
s.close();
}
POJO CLASS:
package dto;
import java.io.Serializable;
import java.sql.Date;
public class LoginRegister implements Serializable{
private int _id;
private String _username = null;
private String _password = null;
Date _last_update = null;
public LoginRegister(){}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String get_username() {
return _username;
}
public void set_username(String _username) {
this._username = _username;
}
public String get_password() {
return _password;
}
public void set_password(String _password) {
this._password = _password;
}
public Date get_last_update() {
return _last_update;
}
public void set_last_update(Date _last_update) {
this._last_update = _last_update;
}
public String toString(){
return
"Id : "+this._id+"\n"+
"Username : "+this._username+"\n"+
"Password : "+this._password+"\n"+
"Last Update : "+this._last_update;
}
}
Configuration File :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database Connection -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- Driver -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Language Used (Dialect) : Here SQL -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property><!-- URL -->
<property name="connection.username">root</property> <!-- Username -->
<property name="connection.password"></property> <!-- Password -->
<!-- To generate SQL Queries when running the program -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- For JDBC Transaction -->
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- Auto Commit -->
<property name="hibernate.connection.autocommit">false</property>
<!-- Mapping Class -->
<mapping class ="Emp.hbm.xml" />
</session-factory>
</hibernate-configuration>
Entity Mapper 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="qqqLoginRegister" table="qqqlogin_register">
<id name="_id" column="id" type="integer">
<generator class="assigned"/>
</id>
<property name="_userName" column="username" type="string"/>
<property name="_password" column="password" type="string"/>
<property name="_last_update" column="last_update" type="date"/>
</class>
</hibernate-mapping>
Locations :
Configuration FIle : srs\Hibernate.cfg.xml
Entity Mapper : src\Emp.hbm.xml
POJO : src\dto\LoginRegister.java
Main Class : src\dao\Index.java
As you are NOT using the Hibernate bean annoatations, in your Hibernate.cfg.xml file, you need to change <mapping class ="Emp.hbm.xml" /> to <mapping resource ="Emp.hbm.xml" />
Hibernate is an ORM framework which maps the Java Bean to a Relational database table and the mapping can be provided directly in the Java Bean Object (using Annotations) or can be provided separately through xml files (like how you did).
Hibernate SessionFactory mappings are compiled from various XML mapping files and <mapping resource is used to load those mapping files (in your case it is a single file which is Emp.hbm.xml file)
You can refer the below documentation for more details:
https://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html

I am getting error for my first hibernate program, please help me to resolve the erros

Errors :
log4j:WARN No appenders could be found for logger
(org.hibernate.cfg.annotations.Version). log4j:WARN Please initialize
the log4j system properly. Exception in thread "main"
org.hibernate.exception.GenericJDBCException: Cannot open connection
at
org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
at
org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at
org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at
org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at org.koushik.hibernate.HibernateTest.main(HibernateTest.java:20)
Caused by: org.postgresql.util.PSQLException: FATAL: database
"5432/hibernatedb" does not exist at
org.postgresql.core.v3.ConnectionFactoryImpl.readStartupMessages(ConnectionFactoryImpl.java:691)
at
org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:207)
at
org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)
at org.postgresql.jdbc.PgConnection.(PgConnection.java:159) at
org.postgresql.Driver.makeConnection(Driver.java:415) at
org.postgresql.Driver.connect(Driver.java:283) at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at
org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
... 5 more
code
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration SYSTEM "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/5432/hibernatedb</property>
<property name="connection.username">postgres</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.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 class="org.javabrains.koushik.dto.UserDetails" />
<!-- <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/> -->
</session-factory>
</hibernate-configuration>
UserDetails.java
package org.javabrains.koushik.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;
}
}
HibernateTest.java
package org.koushik.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.javabrains.koushik.dto.UserDetails;
public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserID(1);
user.setUserName("First user");
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
It looks like it may be an error in your connection URL. Shouldn't it be
jdbc:postgresql://localhost:5432/hibernatedb
?
Check your connection URL path it should be like this:
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
If this doesn't work then note that in PostgreSQL's case it's typical to use port 5432 if it is available. If it isn't, most installers will choose the next free port, usually 5433. So you may enter the property like this
<property name="connection.url">jdbc:postgresql://localhost:5433/hibernatedb</property>
If you still can't figure out then read this line in your stacktrace you may get the idea what #RemyG is trying to say:
org.postgresql.util.PSQLException: FATAL: database "5432/hibernatedb" does not exist at

How to solve this hibernate runtime exception?

I am trying to run following code in eclipse
package com.trial;
import java.sql.*;
import java.io.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class AddStudent {
private static SessionFactory sessionFactory;
public static void main(String args[]) throws Exception {
DataInputStream d = new DataInputStream(System.in);
System.out.println("ENTER YOUR NAME");
String name = d.readLine();
System.out.println("ENTER YOUR DEGREE");
String degree = d.readLine();
System.out.println("ENTER YOUR PHONE");
int phone = Integer.parseInt(d.readLine());
System.out.println("Name: " + name);
System.out.println("Degree: " + degree);
System.out.println("Phone: " + phone);
if ((name.equals("") || degree.equals(""))) {
System.out.println("Information Required");
}
else {
try {
sessionFactory = new Configuration().configure("com//xml//hibernate.cfg.xml").buildSessionFactory();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
Session s = sessionFactory.openSession();
Student stu = new Student();
stu.setName(name);
stu.setDegree(degree);
stu.setPhone(phone);
s.save(stu);
System.out.println("Added to Database");
if (s != null)
s.close();
}
}
}
But getting Runtime exception during creating session factory object that Unable to read XML.
I am using following xml files
hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="studentFactory">
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/ganeshdb</property>
<property name="connection.username">****</property>
<property name="connection.password">****</property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="com//xml//student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Mapping File
<?xml version="1.0"? encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/hibernate-configuration-3.0.dtd">
<hibernate-mapping>
<class name="com.trial.Student" table="studentdemo">
<id name="id" type="int" column="ID">
<generator class="increment" />
</id>
<property name="name" column="name" />
<property name="degree" column="degree" />
<property name="phone" column="phone" />
</class>
</hibernate-mapping>
plz help.
<mapping resource="student.hbm.xml" />
and make sure it is in same direcotry as hibernate.cfg.xml

Hibernate not see a mapping xml file

im new in hibernate and try to write data in DB.
my code
hibernate.cfg.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 name="postsess">
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgis</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.default_schema">public</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Mapping files -->
<mapping resource="net.sf.hibernate.examples.quickstart.Cat.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateUtin
package net.sf.hibernate.examples.quickstart;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import net.sf.hibernate.*;
//import net.sf.hibernate.examples.quickstart.hibernate.cfg.xml;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("Configuration problem: " + ex.getMessage(), ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null) {
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s = (Session) session.get();
session.set(null);
if (s != null)
s.close();
}
}
And get an exeption
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.ExceptionInInitializerError
at net.sf.hibernate.examples.quickstart.hib_main.main(hib_main.java:14)
Caused by: java.lang.RuntimeException: Configuration problem: Resource: net.sf.hibernate.examples.quickstart.Cat.hbm.xml not found
at net.sf.hibernate.examples.quickstart.HibernateUtil.<clinit> (HibernateUtil.java:20)
... 1 more
Caused by: org.hibernate.MappingException: Resource: net.sf.hibernate.examples.quickstart.Cat.hbm.xml not found
at org.hibernate.cfg.Configuration.addResource(Configuration.java:444)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1313)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1285)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1267)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1234)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1162)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1148)
at net.sf.hibernate.examples.quickstart.HibernateUtil.<clinit>(HibernateUtil.java:18)
... 1 more
What im doing wrong. It a second try to execute simple example and again same exeption.
UPDATE
after changing path to mapping file in hibernate.cfg.xml i get another exeption in line session.save(princess);
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): net.sf.hibernate.examples.quickstart.Cat
at org.hibernate.id.Assigned.generate(Assigned.java:32)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:85)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:184)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:173)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:69)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:477)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:472)
at net.sf.hibernate.examples.quickstart.hib_main.main(hib_main.java:23)
Cat.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 15.08.2012 12:46:22 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="net.sf.hibernate.examples.quickstart.Cat" table="CAT">
<id name="id" type="java.lang.String">
<column name="cat_id" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="name" />
</property>
<property name="sex" type="char">
<column name="sex" />
</property>
<property name="weight" type="float">
<column name="weight" />
</property>
</class>
</hibernate-mapping>
and main class.
package net.sf.hibernate.examples.quickstart;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class hib_main
{
/**
* #param args
*/
public static void main(String[] args)
{
Session session = HibernateUtil.currentSession();
Transaction tx= session.beginTransaction();
Cat princess = new Cat();
princess.setName("Princess");
princess.setSex('F');
princess.setWeight(7.4f);
session.save(princess);
tx.commit();
HibernateUtil.closeSession();
}
}
Try to define your mapping resource in such way (using "/" instead of "."):
<mapping resource="net/sf/hibernate/examples/quickstart/Cat.hbm.xml"/>
I think this is a reason of your problem.
UPDATE:
About your second problem - I think that you forgot to define id generation strategy in the Cat.hbm.sql. For example:
<id name="id" column="CREDIT_CARD_ID" type="long">
<generator class="native"></generator>
</id>
UPDATE 2:
Hibernate uses it's own types. So in the declaration of id type yous should use not java.lang.String or java.lang.Integer, but simple string and integer. For example if you want to use string id you should define it as:
<id name="id" column="cat_id" type="integer">
<generator class="native"/>
</id>
Here you can find the list of hibernate's mapping types.
You have two hibernate.cfg.xml.So remove one hibernate.cfg.xml.Try to test with below structure.And resource mapping is not trouble to you.You can declare only like this
<mapping resource="Cat.hbm.xml"/>
You should use / infront of path:
<mapping resource="/net/sf/hibernate/examples/quickstart/Cat.hbm.xml"/>
I would rename Cat.hbm.xml as Cat_hbm_xml as each '.' referring to a sub package.

Categories