Hibernate does not see data inserted from external application - java

I am using Hibernate as an ORM for a server daemon.
This code returns no items if the table associated is empty at run time but has an item added outside of hibernate.
public static List<QueueItem> queue()
{
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
session.flush();
session.clear();
#SuppressWarnings("unchecked")
List<QueueItem> topList = session.createQuery("FROM QueueItem i ORDER BY i.id asc").setMaxResults(3).list();
session.close();
return topList;
}
Here is the hibernate config
<?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>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://10.10.1.4/lanjukebox_test</property>
<property name="hibernate.connection.username">ussqldev</property>
<property name="hibernate.connection.password">ussqldev</property>
<property name="hibernate.jdbc.batch_size">25</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">validate</property>
<!-- List of XML mapping files -->
<mapping resource="usagisoft/lan/jukebox/domain/entities/Song.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/Id3.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/QueueItem.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/Vote.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
If I create an object and persist it from within the application it works fine, If there is already data in the table and I insert the data it finds the other objects, the issue arises as soon as the table is empty during run time.
This is a big issue because another application handles the inserting of data for these objects.
I am using hibernate 4.2.7.Final with Java 1.7(jdk1.7.0_45) in eclipse.

You can resolve this problem since
hibernate.cfg.xml
adding this tag:
<property name="hibernate.connection.autocommit">true</property>

Related

Connect to a database dynamically in hibernate

So I have multiple pluggable databases (PDBs) and I want to connect to any one of them dynamically using Hibernate. How do I achieve such functionality?
To connect to PDB1 (and likewise for other PDBs), I have:
protected void setupPdb1() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure("hibernate-1.cfg.xml") // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory1 = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception ex) {
StandardServiceRegistryBuilder.destroy(registry);
throw new RuntimeException(ex);
}
}
My hibernate config file corresponding to PDB1 is as follows:
<?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.url">jdbc:oracle:thin:#//localhost:1521/pdb1.oradev.oraclecorp.com</property>
<property name="connection.username">test</property>
<property name="connection.password">password12</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<mapping class="net.codejava.hibernate.Book" />
</session-factory>
</hibernate-configuration>
The issue with this approach is there is one config file for each PDB. How do I dynamically select the PDB to connect to using Hibernate?
it depends on your strategy, what is the trigger to switch database ?

Every time I run server my new table is being created and previous data are deleted

Whenever I run my server my database table are re-created and all my previous data are being deleted. I was thinking this might be the problem in hibernate configuration file but don't know the actual reason hope you awesome guys will figure me out .
I also tried changing <property name="hibernate.hbm2ddl.auto">update</property> to auto , validate but didnot help
<?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>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/restro
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root
</property>
<!-- <property name="connection.release_mode">auto</property> -->
<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Names the annotated entity class -->
<mapping class="com.restroo.model.MenuItems"/>
<mapping class="com.restroo.model.AdminUser"/>
</session-factory>
</hibernate-configuration>

Hibernate returning empty list instead of throwing exceptions

I am just concerned, why while using Hibernate criteria from http://www.tutorialspoint.com/hibernate/hibernate_criteria_queries.htm
Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary", 2000));
List results = cr.list();
If in my database Employee class does not have salary column, or even worse - Employee is not mapped, results will be an empty list and hibernate will not throw errors.
I thought it is the problem of implicit-polymorphism, but firstly Im not extenting anything, secondly if I'll use session.delete, session.save, session.update everything goes correctly and I get all those exceptions like NoSuchFieldException, UnknownEntity and so on.
But while getting objects using criteria - just empty list.
Is it as it supposed to be? Can I somehow check if class/field I am searching for exists in DB?
All the questions about it on StackOverflow concerns the problem, when criteria returns empty list, while they have got objects in database.
I want to know why my criteria returns empty list, while it should throw error...
Mine hibernate config file:
`
<?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">******</property>
<property name="hibernate.connection.url">*******</property>
<property name="hibernate.connection.username">******</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.search.autoregister_listeners">false</property>
<property name="hibernate.show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<mapping resource="employee.hbm.xml" />
</session-factory>
</hibernate-configuration>
`

org.hibernate.TransactionException: Unable to locate JTA UserTransaction

I am writing my first example for Inserting Record using Hibernate Framework .
To start with I am trying to following instructions given at URL
You can see my code at GIT Hibernate Basic
When calling below piece of code
public Long saveEmployee(Employee emp){
Session session = new Configuration().configure().buildSessionFactory().openSession();
session.beginTransaction();
Long id = (Long) session.save(emp);
session.getTransaction().commit();
session.close();
return id;
}
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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">root123</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">2</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.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<!-- validate | update | create | create-drop -->
<!-- validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session. -->
<property name="hbm2ddl.auto">validate</property>
<!-- added as suggested in below answer-->
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property>
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
It throws org.hibernate.TransactionException: Unable to locate JTA UserTransaction
Details :
I am not deploying the application from any Application server I am running it as plan Java application.
I am using Hibernate 4.1
Is it neccessary to deploy it in Application Server ?
Whether we have to explicitly specify the JTAUsertransaction in Hibernate 4.1 version?
=============== Update ==============
With
hibernate.transaction.factory_class = org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
Solved this error and I can execute the program .
But I still wanted to know the reason why its not working when using org.hibernate.transaction.JTATransactionFactory
When used
hibernate.transaction.factory_class = org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
Solved this error and I can execute the program.
I have deliberately posted it as an answer so it would be helpful for someone.
You would be missing the JTA configuration in your hibernate config file
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property>

Hibernate: table thingsdb.Things doesn't exist

I am trying to retrieve all my Things from the database using Hibernate, but I get this error:
Table 'thingsdb.Things' doesn't exist org.hibernate.exception.SQLGrammarException: could not execute query
The table in the database is actually named things, not Things.
The query I am executing is the following:
List<Thing> listofthings = session.createQuery(" from Thing thing").list();
And the hibernate xml:
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/mythings</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">5</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<mapping class="mythings.Thing" />
</session-factory>
</hibernate-configuration>
I tried to search for a solution but I didn't find it. I am new to Hibernate so I don't really know what to look for or where.
You will need to set the name of the table, otherwise it tries to build the query with the default name which is the class name:
#Entity
#Table(name="thing")
public class Thing {
...
}

Categories

Resources