Hibernate 3: unable to query PostgreSQL database - java

I am setting up a project using Hibernate 3.3.1 GA and PostgreSQL 8.3. I've just created a database, the first table, added one row there and now configuring Hibernate.
However, even the simplest query:
Criteria criteria = session.createCriteria(Place.class);
List result = criteria.list();
could not be executed (empty list is returned though there is one record in the database). I looked at the PostgreSQL logs to see:
2008-09-17 22:52:59 CEST LOG: connection received: host=192.168.175.1 port=2670
2008-09-17 22:52:59 CEST LOG: connection authorized: user=... database=...
2008-09-17 22:53:00 CEST LOG: execute <unnamed>: SHOW TRANSACTION ISOLATION LEVEL
2008-09-17 22:53:02 CEST LOG: could not receive data from client: Connection reset by peer
2008-09-17 22:53:02 CEST LOG: unexpected EOF on client connection
2008-09-17 22:53:02 CEST LOG: disconnection: session time: 0:00:03.011 user=... database=... host=192.168.175.1 port=2670
I wrote a simple program using plain JDBC to fetch the same data and it worked. PostgreSQL logs in this case look like this (for comparison):
2008-09-17 22:52:24 CEST LOG: connection received: host=192.168.175.1 port=2668
2008-09-17 22:52:24 CEST LOG: connection authorized: user=... database=...
2008-09-17 22:52:25 CEST LOG: execute <unnamed>: SELECT * from PLACE
2008-09-17 22:52:25 CEST LOG: disconnection: session time: 0:00:00.456 user=... database=... host=192.168.175.1 port=2668
Hibernate debug log does not indicate any errors. If I take the query listed in the logs:
15:17:01,859 DEBUG org.hibernate.loader.entity.EntityLoader: Static select for entity com.example.data.Place: select place0_.ID as ID0_0_, place0_.NAME as NAME0_0_, place0_.LATITUDE as LATITUDE0_0_, place0_.LONGITUDE as LONGITUDE0_0_ from PLACE place0_ where place0_.ID=?
and execute it agains the database in the psql, it works (this means that Hibernate has generated a proper SQL).
Below is the Hibernate configuration:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:postgresql://192.168.175.128:5433/...</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.username">...</property>
<property name="hibernate.connection.password">...</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.use_outer_join">true</property>
<mapping resource="com/example/data/Place.hbm.xml"/>
</session-factory>
</hibernate-configuration>
...and the mapping file:
<hibernate-mapping package="com.example.data">
<class name="com.example.data.Place" table="PLACE">
<id column="ID" name="id" type="java.lang.Integer">
<generator class="native"/>
</id>
<property column="NAME" name="name" not-null="true" type="java.lang.String">
<meta attribute="use-in-tostring">true</meta>
</property>
<property column="LATITUDE" name="latitude" not-null="true" type="java.lang.Float">
<meta attribute="use-in-tostring">true</meta>
</property>
<property column="LONGITUDE" name="longitude" not-null="true" type="java.lang.Float">
<meta attribute="use-in-tostring">true</meta>
</property>
</class>
</hibernate-mapping>
Googling for unexpected EOF log entry was not friutful. Any ideas, community?

After applying debugger to the Hibernate code, it is fixed!
It is not visible in the question's text, but the problem is that Place passed to the createCriteria() method is from another package, not com/example/data, specified in the configuration XML files.
Hibernate invokes Class.isAssignableFrom(), and if false is returned, it exits silently, thus breaking the connection. I will open a ticket for Hibernate developers on this matter.

Related

Hibernate ORA-00932: inconsistent datatypes: expected NUMBER got BINARY

I'm trying to map an Oracle database with Java using Hibernate but I'm facing an issue. Here is the code :
Java app :
package guival.tp3.bdd;
import java.time.LocalDate;
import org.hibernate.*;
public class Scenariste extends Personne {
private int idScenariste;
public int getIdScenariste() {
return idScenariste;
}
public void setIdScenariste(int idScenariste) {
this.idScenariste = idScenariste;
}
}
public class Test {
public static void main(String[] args) {
Session uneSession = HibernateUtil.getSessionFactory().openSession();
Transaction uneTransaction = uneSession.beginTransaction();
Scenariste scenar = new Scenariste();
scenar.setDateNaissance(LocalDate.now());
scenar.setNom("fefef");
scenar.setPrenom("fefzefzfz");
uneSession.save(scenar);
uneTransaction.commit();
uneSession.close();
HibernateUtil.shutdown();
}
}
Hibernate config file :
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521/system</property>
<property name="hibernate.connection.username">---</property>
<property name="hibernate.connection.password">---</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</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>
<!-- SQL to stdout logging -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<mapping resource="guival/tp3/bdd/Scenariste.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Hibernate Scenariste table mapping file :
<hibernate-mapping>
<class name="guival.tp3.bdd.Scenariste" table="SCENARISTE">
<id name="idScenariste" column="ID_SCENARISTE" type="integer" unsaved-value="0">
<generator class="sequence">
<param name="sequence">SEQ_SCENARISTE</param>
</generator>
</id>
<property name="nom">
<column name="NOM" sql-type="VARCHAR2(50)"/>
</property>
<property name="prenom">
<column name="PRENOM" sql-type="VARCHAR2(50)"/>
</property>
<property name="dateNaissance">
<column name="DATE_NAISSANCE" sql-type="DATE"/>
</property>
</class>
</hibernate-mapping>
And the SCENARISTE table looks like that :
I also made a trigger in the database to increment the ID_SCENARISTE column.
When I run this code I have this error : ORA-00932: inconsistent datatypes: expected NUMBER got BINARY
Here are the last lines of the Hibernate log when the error occurs :
Hibernate:
select
SEQ_SCENARISTE.nextval
from
dual
Hibernate:
/* insert guival.tp3.bdd.Scenariste
*/ insert
into
SCENARISTE
(NOM, PRENOM, DATE_NAISSANCE, ID_SCENARISTE)
values
(?, ?, ?, ?)
déc. 02, 2018 6:48:55 PM org.hibernate.util.JDBCExceptionReporter logExceptions
WARNING: SQL Error: 932, SQLState: 42000
déc. 02, 2018 6:48:55 PM org.hibernate.util.JDBCExceptionReporter logExceptions
SEVERE: ORA-00932: types de données incohérents ; attendu : NUMBER ; obtenu : BINARY
I'm using Hibernate 3.2.0.cr5 and Java SE 8.
Do you have a solution ?
Try removing the data type like this
<id name="idScenariste" column="ID_SCENARISTE" unsaved-value="0">
<generator class="sequence">
<param name="sequence">SEQ_SCENARISTE</param>
</generator>
</id>

Hibernate Authentication Error with SQL Server

I am having a difficult time trying to set a connection with hibernate to a SQL Server. I should create a connection to the following data source DataSource=server,port. It seem strange that the port must be specify with a comma instead of :
When I connect to it through Visual Studio 2012 this is how it looks:
Data Source=server,17001;Initial Catalog=database;User ID=username
In order to connect it I create the following hibernate configuration file:
<hibernate-configuration>
<session-factory name="">
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://server.fqdn</property>
<property name="hibernate.connection.port">port</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.databasename">database</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<property name="connection.pool_size">1000</property>
</session-factory>
</hibernate-configuration>
But I get the following Exception when the connection is attempted:
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'username'. ClientConnectionId:c619c1dc-2c6c-4c6e-bc81-7d3619ee9ff1
I know for sure that the user and password are correct as I am using them to connect to the database through Visual Studio 2012 and they works fine.
Any idea of how should I face it?
I forgot to mark this as resolved. The issue was that I was specifying the port as a separate property:
<property name="hibernate.connection.port">port</property>.
When I add it to the connection string parameter
<property name="hibernate.connection.url">jdbc:sqlserver://server.fqdn:port</property>
it works

Duplicate key or integrity constraint violation message from server in Hibernate

I'm new to Hibernate. I'm trying to insert records into my MySQL DB. The first record was inserted properly when I run the Java application, and when I change the details in the code and try to run it again. It throws me error of Duplicate key or integrity constraint. My XML is
<?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="com.college.Student" table="STUDENT">
<id column="ID" name="id" type="long" />
<property column="STUDENT_NAME" name="name" type="string" />
<property column="DEGREE" name="degree" type="string" />
<property column="ROLL" name="roll" type="string" />
<property column="PHONE" name="phone" type="string" />
</class>
</hibernate-mapping>
I guess I need to change in this configuration file or Hibernate.cfg.xml because its a primary key . Please suggest me.
Following is the error
WARN: SQL Error: 1062, SQLState: 23000
Feb 18, 2016 11:49:36 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate key or integrity constraint violation message from server: "Duplicate entry '0' for key 'PRIMARY'"
Feb 18, 2016 11:49:36 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Feb 18, 2016 11:49:36 AM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)
Seems like you haven't incremented your primary key column, you will have to do something like this
<id column="ID" name="id" type="long" >
<generator class="increment" />
</id>
You need to give generator for primary key of your table which will auto generated.
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
Read this
You need to have an auto increment for an id column.
For MySQL the best choice is to use identity generator, because of MySQL supports it natively.
<id column="ID" name="id" type="long">
<generator class="identity"/>
</id>
Hibernate will create a table with auto_increment column and MySQL will care about auto increment id
create table STUDENT (
ID bigint not null auto_increment,
...
)
Using other generators is not optimal, because of Hibernate will use additional queries and a table (hibernate_sequence) to increment id.

getGeneratedKeys() support is not enabled error in Hibernate 5.0.0.CR2

I'm trying to connect to Oracle and I'm getting this error in Hibernate-5.0 even though I have enabled this property in configuration.
> Aug 10, 2015 8:49:34 AM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
Aug 10, 2015 8:49:35 AM org.hibernate.AssertionFailure <init>
ERROR: HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: getGeneratedKeys() support is not enabled
Exception in thread "main" org.hibernate.AssertionFailure: getGeneratedKeys() support is not enabled
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.checkAutoGeneratedKeysSupportEnabled(StatementPreparerImpl.java:94)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareStatement(StatementPreparerImpl.java:113)
at org.hibernate.id.SequenceIdentityGenerator$Delegate.prepare(SequenceIdentityGenerator.java:93)
My hibernate.cfg.xml is as below.
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">*****</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#*****</property>
<property name="hibernate.connection.username">*****</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.jdbc.use_get_generated_keys">true</property>
<property name="show_sql">true</property>
<property name="connection.pool_size">1</property>
<!-- List of XML mapping files -->
<mapping resource="mapping/Employee.hbm.xml" />
</session-factory>
And Employee.hbm.xml is like below
<hibernate-mapping>
<class name="domain.Employee" table="EMPLOYEE">
<id name="id" type="integer" column="id">
<generator class="sequence-identity">
<param name="sequence">EMP_SEQ</param>
</generator>
</id>
<property name="firstName" column="first_name" type="string" />
<property name="lastName" column="last_name" type="string" />
<property name="salary" column="salary" type="integer" />
</class>
I have tried many times but not seem to resolve. Where I'm going wrong here? Any pointers is a great help. Thanks in advance.
Not sure if this is an issue with the Hibernate version, because when I change the dependency version to 4.3.9.Final from 5.0.0.CR2 in POM then it is working fine.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.9.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.9.Final</version>
</dependency>
I don't think it is your code that is the problem, but Oracle.
According to comments in the Oracle9Dialect, Oracle does not support returning the generated key, not like any other database does it.

Loading BLOB table from H2 embedded with Hibernate

I have an application that has to run with an Oracle or embedded H2 database depending on the environment. Up till now I used a MySQL database instead of the embedded H2 one, but decided to migrate.
I use Hibernate 3.3.1GA (and am restricted, so I cannot update). With both Oracle and MySQL everything works fine, but when I try to use the H2 database it keeps hanging. The problem appears to be a column with BLOBs (serialized java objects). Even when the table is empty, execution hangs.
SLF4J output (loglevel ALL):
TableMetadata.java:org.hibernate.tool.hbm2ddl.TableMetadata:<init>:62 INFO table found: DATABASE.PUBLIC.JAVA_OBJECTS
org.hibernate.tool.hbm2ddl.TableMetadata:<init>:63 INFO columns: [id, last_update, markdeleted, class, object]
org.hibernate.connection.DriverManagerConnectionProvider:closeConnection:152 TRACE returning connection to pool, pool size: 1
At this point the program seems to hang. Earlier log output seems normal and when this table is not used (removed from hibernate.cfg.xml) the program starts up fine.
hibernate.cfg.xml (excerpt)
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">jdbc:h2:file:database</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.default_schema">PUBLIC</property>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
The table's create string:
CREATE TABLE java_objects (
id int(11) NOT NULL AUTO_INCREMENT,
class varchar(255) NOT NULL,
object blob NOT NULL,
last_update timestamp AS CURRENT_TIMESTAMP,
markDeleted tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (id)
) ;
and finally the entity xml
<hibernate-mapping>
<class name="server.DataBean" table="java_objects">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="type" column="class" />
<property name="object" not-null="true">
<column name="object" sql-type="BLOB" />
</property>
<property name="lastUpdate" column="last_update" type="timestamp" />
<property name="markDeleted" type="boolean" />
</class>
</hibernate-mapping>
Does anyone know what I'm doing wrong? What is h2 expecting differently when handling blobs?
Problem may have been with org.hibernate.dialect.H2Dialect
Changing to HSQLDialect works. Still, is there an underlying issue?

Categories