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
Related
Maybe it is a simple question, but I can't find out this situation of relations in Hibernate.
I have these Entities:
#Entity
public class User {
...
#OneToMany(mappedBy = "user")
private Set<Conversation> posts = new HashSet<Conversation>();
...
}
#Entity
public class Conversation {
...
#OneToMany(mappedBy = "conversation")
private Set<Message> messages = new HashSet<Message>();
...
}
#Entity
public class Message { ... }
and then I want create User with Conversation and Message at once. Idea should be like this:
User user = new User();
user.getPosts().add(new Conversation(){
{
getMessages().add(new Message());
}
});
session.persist(user);
But just User is saved in database - why isn't it all? Because of default LAZY fetching? Could my idea be implemented somehow?
PS: Of course I know about the solution of persisting each of the entities, but I am used to do like this in other frameworks like nette or Django, so I can't get out of my head.
PPS: I found out that problem is in default CascadeType. Could it be set on globally, e.g. in Hibernate config XML? Is it a good idea (by performance point of view - it is persisted each time on "superpersist" or only in case of changes)?
PPPS: I also found out (opposite to Django) that I have to set FK ex-post for each item added to collection. It is natural (because of selected pure Set type), but new for me. Which approach would you recommend me? Required FK as argument in constructor on item Entity e.g.:
Class Message{
Message(Conversation conversation){
setConversation(conversation);
}
...
}
or make a method for adding where FK sets inside e.g.:
Class Conversation{
...
public void addMessage(Message msg){
msg.setConversation(this);
getMessages().add(msg);
}
...
}
?
Making Session + configure XML.
private final static String CFG = "hibernate-cfg.xml";
private final static String SCRIPT_FILE = "query.sql";
private static SessionFactory sessionFactory;
private static ServiceRegistry buildRegistry() {
return new StandardServiceRegistryBuilder()
.configure(CFG)
.build();
}
private static Metadata getMetaData() {
return new MetadataSources(buildRegistry()).getMetadataBuilder().build();
}
private static SessionFactory buildSessionFactory() {
return getMetaData().getSessionFactoryBuilder().build();
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}
public static Session getSession(){
try {
return getSessionFactory().openSession();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
and the 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>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/learnme
</property>
<property name="connection.username">root</property>
<property name="connection.password"/>
<property name="connection.pool_size">100</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</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.NoCacheProvider
</property>
<!-- Display all generated 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="learnme.hibernate.entities.User"/>
<mapping class="learnme.hibernate.entities.Conversation"/>
<mapping class="learnme.hibernate.entities.Message"/>
</session-factory>
</hibernate-configuration>
According to this and this
you need to have this in your persistence.xml file to set it globally:
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_1_0.xsd" version="1.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<cascade-persist/>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
The mapping file has to be located either in the default location,
META-INF/orm.xml, or in another location that is specified explicitly
in the persistence unit definition (in persistence.xml).
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
We are using hibernate to populate a ddbb with data from multiples files. Multiples threads are proccessing the files and when x files are processed we flush the data on the database.
When i try to write on the database we get the next error:
core.exception.SavingException: org.hibernate.MappingException: Unknown entity: FilesPT
at databaseaccess.session.GenericManagerImpl.insertBatch(GenericManagerImpl.java:75)
at FileWriter.flushFiles(FileWriter.java:425)
Caused by: org.hibernate.MappingException: Unknown entity: FilesPT
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:597)
at org.hibernate.impl.StatelessSessionImpl.getEntityPersister(StatelessSessionImpl.java:376)
at org.hibernate.impl.StatelessSessionImpl.insert(StatelessSessionImpl.java:80)
at databaseaccess.dao.GenericDAOImpl.insertList(GenericDAOImpl.java:36)
at session.GenericManagerImpl.insertBatch(GenericManagerImpl.java:72)
... 4 more
My Hibernate config file is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"classpath://org/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#%DB_HOST%:%DB_PORT%:%DB_SID%</property>
<property name="hibernate.connection.username">%DB_USER%</property>
<property name="hibernate.connection.password">%DB_PASS%</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.default_schema">%DB_SCHEMA%</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.format_sql">false</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<mapping resource="databaseaccess/entities/Files.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The file databaseaccess/entities/Files.hbm.xml has two different entities:
<hibernate-mapping>
<class name="databaseaccess.entities.Files" table="FILES_PT" entity-name="FilesPT">
<id name="dealId" column="FILE_ID" type="java.lang.String" length="50" />
<property name="filename" column="FILENAME" type="java.lang.String" length="250" />
<property name="folder" column="FOLDER" type="java.lang.String" length="30" />
</class>
<class name="databaseaccess.entities.Files" table="FILES_ES" entity-name="FilesES">
<id name="dealId" column="FILE_ID" type="java.lang.String" length="50" />
<property name="filename" column="FILENAME" type="java.lang.String" length="250" />
<property name="folder" column="FOLDER" type="java.lang.String" length="30" />
</class>
</hibernate-mapping>
To save the data we are using an Stateless session generated from the hibernateUtil:
public void insertList(final String entityName, final Collection entities) {
StatelessSession session = HibernateUtil.openStatelessSession();
try {
Transaction tx = session.beginTransaction();
try {
for (Object entity : entities) {
session.insert(entityName, entity);
}
tx.commit();
} catch (final HibernateException e) {
logger.error("Error inserting " + entities.size() + " rows in database. " + e.getMessage() + ":\n "
+ e.getMessage());
throw e;
} finally {
tx.rollback();
}
} finally {
session.close();
}
}
The hibernate util generate a static session factory
static {
try {
// Create the SessionFactory from config file.
File fileCfgHibernate = new File(ConfigurationManager.getProperty("Global.properties", "HIBERNATE_CFG_FILE"));
logger.info("Opening DB session with configuration from: " + fileCfgHibernate.getPath());
Configuration cfgHibernate = new Configuration().configure(fileCfgHibernate);
sessionFactory = cfgHibernate.buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
logger.error("DB session creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static StatelessSession openStatelessSession() {
return sessionFactory.openStatelessSession();
}
We have checked that the session factory use the configuration on the hibernate.cfg file but it seems that the session is not getting the configuration. What are we missing?
I have used EclipseLink till now, but now I'm trying a Java SE project with Hibernate 4. I'm trying to do perform a NamedQuery but I get the following exception:
HibernateLog --> 18:05:03 ERROR org.hibernate.internal.SessionFactoryImpl - HHH000177: Error in named query: SubCategory.findAll
org.hibernate.hql.internal.ast.QuerySyntaxException: Subcategory is not mapped [SELECT s from Subcategory s]
This is my DBUtils class
public class DBUtils {
static final Logger logger = Logger.getLogger(DBUtils.class);
private static final ServiceRegistry serviceRegistry;
private static final SessionFactory sessionFactory;
/**
*
*/
//initialize session factory;
static {
try {
Configuration conf = new Configuration()
// mapped classes;
.addAnnotatedClass(Category.class)
.addAnnotatedClass(SubCategory.class)
.configure();
//.....
serviceRegistry = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
sessionFactory = conf.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
logger.error("Initial SessionFactory creation failed");
System.err.println("." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static synchronized SessionFactory getSessionFactory() {
return sessionFactory;
}
}
And this is my hibernate.cfg.xml
<?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 -->
<!-- Ommitted... -->
<!-- JDBC connection pool, use Hibernate internal connection pool -->
<property name="connection.pool_size">5</property>
<!-- Defines the SQL dialect used in Hibernate application -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- hibernate sql output -->
<property name="show_sql">false</property>
<property name="format_sql">false</property>
<property name="use_sql_comments">false</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.connection.useUnicode">true</property>
<property name="hibernate.connection.characterEncoding">utf8</property>
<property name="hibernate.connection.CharSet">utf8</property>
</session-factory>
</hibernate-configuration>
Finally my entities are all annotated with #Entity("tableName") annotation
What am I doing wrong?
Hibernate is case sensitive and uses the class name to map an Entity in its HQL. So
SELECT s from Subcategory s
will refer to an entity class called Subcategory. This is wrong. Use the actual class name
SELECT s from SubCategory s
as your class is named SubCategory, seen in
.addAnnotatedClass(SubCategory.class)
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.