How to solve this hibernate runtime exception? - java

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

Related

Cannot get a connection as the driver manager is not properly initialized on hibernate

I am learning Hibernate and I dont understand why am I getting this error launching program:
java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:172)
at net.codejava.hibernate.VueloManager.setup(VueloManager.java:15)
at net.codejava.hibernate.VueloManager.main(VueloManager.java:54)
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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://127.0.0.1:3306/vuelos_lite</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="net.codejava.hibernate.Vuelo" />
<mapping class="net.codejava.hibernate.Pasajero" />
<mapping class="net.codejava.hibernate.Pasaje" />
</session-factory>
</hibernate-configuration>
VueloManager class. This is the main class of the program:
public class VueloManager {
protected SessionFactory sessionFactory;
protected void setup() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception ex) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
protected void read() {
Session session = sessionFactory.openSession();
String identificadorId = "BRU-2222";
Vuelo vuelo = session.get(Vuelo.class, identificadorId);
System.out.println("Id: " + vuelo.getIdentificador());
System.out.println("Fecha: " + vuelo.getDate());
System.out.println("Tipo Vuelo: " + vuelo.getTipo_vuelo());
exit();
}
public static void main(String[] args) {
VueloManager manager = new VueloManager();
manager.setup();
//manager.read();
manager.exit();
}
}
I have checked hibernate.cfg.xml connections and all is fine.

Hibernate rebuilds tables of DB

I have very simple maven + hibernate project.
I want to retrieve data and print it in console with the command "select * from product". But each time i launch my app, it rebuilds all tables in db, as a result all data is removed.
What should I do so tables are not rerebuilt each time I launch my app?
Main.java
public class Main {
static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
List<Object> products = null;
try {
session.beginTransaction();
SQLQuery query = session.createSQLQuery("select * from product");
query.addEntity(Product.class);
products = query.list();
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
sessionFactory.close();
}
System.out.println("Hello");
for (Iterator iterator = products.iterator(); iterator.hasNext(); ) {
Product product = (Product) iterator.next();
logger.info("Hello");
}
}
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="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">****</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.jdbc.lob.non_contextual_creation">true</property>
<mapping class="models.User"/>
<mapping class="models.Role"/>
<mapping class="models.Product"/>
<mapping class="models.ProductCategory"/>
<mapping class="models.Order" />
</session-factory>
</hibernate-configuration>
Change your line
<property name="hbm2ddl.auto">create</property>
by
<property name="hbm2ddl.auto">validate</property>
Look also https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl
Use following code in your hibernate.cfg.xml file
<property name="hbm2ddl.auto">Update</property>
instead of
<property name="hbm2ddl.auto">create</property>

HIbernate Stateless Session entity configuration

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?

How to mock the database session for HSQL DB Junit

I have a repository implementation class as below.
public class TesepositoryImpl extends OTPRepositoryBase implements
TestRepository {
public TesepositoryImpl() {
super(RequiresOTPSession.YES);
}
#Override
public int createPreference(AirDetail AirDetail)
throws PersistenceException {
Transaction tx = null;
Session session = null;
try {
session = otpDatabaseSession.openSession();
tx = session.beginTransaction();
session.save(AirDetail);
tx.commit();
} finally {
otpDatabaseSession.closeSession(session);
}
return AirDetail.getAirDetailId().intValue();
}
I have stated writting junit for the above
public class TesRepositoryImplTest {
private EmbeddedDatabase db;
#Before
public void setUp() {
db = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
.addScript("db/sql/create-db.sql")
.addScript("db/sql/insert-data.sql").build();
}
TesRepository testRepository = new TestRepositoryImpl();
#Test
public void createPreference() throws Exception {
//*setting values** creating preference**/
int airRefereID = testRepository
.createPreference(preference);
}
#After
public void tearDown() {
db.shutdown();
}
i defined hibernate cfg file as below
<?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">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:fcds</property>
<property name="connection.username">SA</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="connection.autocommit">true</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.standard_service_registry_builder">false</property>
<mapping class="com.aa.dotc.commons.domain.preference" />
</session-factory>
</hibernate-configuration>
I need to know the below.
When I call testRepository
.createPreference(preference);
I need to override the otpsession to HSQL session.
Kindly help me how to achieve the above using HSQL or share any samples to achieve the same.

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