Hibernate created table not able to see in H2 - java

I am able to create the table successfully through hibernate in Java application but not able to see the same in the H2 database. May be I need another pair of eyes to look into this problem?
Here is my config file.
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:~/hibernateDB;DB_CLOSE_ON_EXIT=TRUE;MVCC=FALSE;MV_STORE=FALSE;FILE_LOCK=NO</property>
<property name="connection.username">vijayasunil</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.use_query_cache">false</property>
<property name="cache.use_second_level_cache">false</property>
<property name="cache.use_structured_entries">true</property>
<property name="cache.region.factory_class">org.hibernate.cache.internal</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.learning.hibernate.dto.UserDetails"/>
</session-factory>
</hibernate-configuration>
The H2 Console looks like as below
H2 Console
The Java Hibernate console is saying as table is created.
Mar 22, 2016 11:15:04 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
Mar 22, 2016 11:15:04 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 22, 2016 11:15:04 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Mar 22, 2016 11:15:05 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 22, 2016 11:15:05 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Mar 22, 2016 11:15:05 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.h2.Driver] at URL [jdbc:h2:~/hibernateDB;DB_CLOSE_ON_EXIT=TRUE;MVCC=FALSE;MV_STORE=FALSE;FILE_LOCK=NO]
Mar 22, 2016 11:15:05 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=vijayasunil, password=****}
Mar 22, 2016 11:15:05 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Mar 22, 2016 11:15:05 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Mar 22, 2016 11:15:05 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: drop table TEST_DETAILS if exists
Hibernate: create table TEST_DETAILS (userId integer not null, userName varchar(255), primary key (userId))
Mar 22, 2016 11:15:06 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#2250b9f2'
*********
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])
*********
Hibernate: insert into TEST_DETAILS (userName, userId) values (?, ?)
Entity class in Java code as below
#Entity(name="TEST_DETAILS")
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;
}
}
Updating the Database by using the below piece of code
public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("Test User");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}

Related

Cannot connect to Informix using Hibernate

I'm trying to connect to Informix database using Hibernate 5.2.10, but the program doesn't respond and gets stuck without throwing any error message.
I can't find anything from the console . Any suggest on what mistake I made? I'm new to Hibernate
hibernate.cfg.xml
<property name="connection.driver_class">com.informix.jdbc.IfxDriver</property>
<property name="connection.url">jdbc:informixsqli://****:1528/****:informixserver=*****</property>
<property name="connection.username">*****</property>
<property name="connection.password">*****</property>
Console:
Sep 17, 2017 11:05:55 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
Sep 17, 2017 11:05:55 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 17, 2017 11:06:05 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Sep 17, 2017 11:06:05 AM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH010002: C3P0 using driver: com.informix.jdbc.IfxDriver at URL: jdbc:informix-sqli://d7uat:1528/d7main:informixserver=uatserver
Sep 17, 2017 11:06:05 AM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001001: Connection properties: {user=******, password=****}
Sep 17, 2017 11:06:05 AM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001003: Autocommit mode: false
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Sep 17, 2017 11:06:07 AM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001007: JDBC isolation level: <unknown>
Sep 17, 2017 11:06:08 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.InformixDialect
Sep 17, 2017 11:06:14 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#7a0ef219] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
HibernateUtil
private static final SessionFactory sessionFactory = buildSessionFactory();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
private static SessionFactory buildSessionFactory(){
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try {
return new
MetadataSources(registry).buildMetadata().buildSessionFactory();
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
StandardServiceRegistryBuilder.destroy( registry );
throw new ExceptionInInitializerError(ex);
}
}
InformixTest
public static CustomerInvoice lookupInvoice(String invoiceNumber){
Session session = null;
List<CustomerInvoice> customerInvoiceList = new ArrayList<CustomerInvoice>();
CustomerInvoice customerInvoice = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
Query query = session.createQuery(invoiceByNumber);
query.setParameter("invoiceNumber", invoiceNumber+"%");
customerInvoiceList = ((org.hibernate.query.Query) query).list();
} catch (Exception e) {
e.printStackTrace();
session.close();
} finally {
if (session != null && session.isOpen()) {
session.close();
}
}
if(customerInvoiceList.size()>0){
customerInvoice = customerInvoiceList.get(0);
}
return customerInvoice;
}
I did a quick test with 5.2 and the latest jdbc driver and it appears to work fine for me. I'm using your HiberanateUtil and a similar Hibernate config file:
D:\Infx\work\Hibernate>java list
Sep 18, 2017 10:53:49 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.11.Final}
Sep 18, 2017 10:53:49 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 18, 2017 10:53:49 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Sep 18, 2017 10:53:50 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Sep 18, 2017 10:53:50 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Sep 18, 2017 10:53:51 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Sep 18, 2017 10:53:51 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.informix.jdbc.IfxDriver] at URL [jdbc:informix-sqli://420ito:9088/stores7:INFORMIXSERVER=ids1210;user=informix;password=dummy;]
Sep 18, 2017 10:53:51 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {}
Sep 18, 2017 10:53:51 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Sep 18, 2017 10:53:51 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sep 18, 2017 10:53:52 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.InformixDialect
Sep 18, 2017 10:53:53 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#37ebc9d8] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Sep 18, 2017 10:53:55 AM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select state0_.id as id1_0_, state0_.code as code2_0_, state0_.sname as sname3_0_, state0_.next_state_id as next_sta4_0_ from States state0_ order by state0_.id asc
test, test
test, test
Sep 18, 2017 10:53:55 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:informix-sqli://420ito:9088/stores7:INFORMIXSERVER=ids1210;user=informix;password=dummy;]
D:\Infx\work\Hibernate>
Only way I get something like a 'hang' is if I get an exception during the open session(). I forced one compiling the method with an old Hibernate version library (3.x) which doesn't have 'classic' methods:
D:\Infx\work\Hibernate>java list
Sep 18, 2017 10:54:42 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.11.Final}
Sep 18, 2017 10:54:42 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Sep 18, 2017 10:54:42 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Sep 18, 2017 10:54:42 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Sep 18, 2017 10:54:42 AM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
Sep 18, 2017 10:54:44 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Sep 18, 2017 10:54:44 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.informix.jdbc.IfxDriver] at URL [jdbc:informix-sqli://420ito:9088/stores7:INFORMIXSERVER=ids1210;user=informix;password=dummy;]
Sep 18, 2017 10:54:44 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {}
Sep 18, 2017 10:54:44 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Sep 18, 2017 10:54:44 AM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Sep 18, 2017 10:54:44 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.InformixDialect
Sep 18, 2017 10:54:46 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#37ebc9d8] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;
at list.main(list.java:12)
....
....
....
As yours, 'last' INFO message is "Connection obtained from JdbcConnectionAccess" , but after that I'm also getting the nosuchmethod exception. I have to press control+c to get out.
Maybe your exceptions are been sent somewhere else ;)
EDIT
This is the code I'm using to test it directly from the console, should be everything you need to run it.
D:\Infx\work\Hibernate>cat set5.cmd
#echo off
set CLASSPATH=
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\javassist-3.20.0-GA.jar
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\dom4j-1.6.1.jar
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\hibernate-jpa-2.1-api-1.0.0.Final.jar
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\hibernate-core-5.2.11.Final.jar
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\hibernate-commons-annotations-5.0.1.Final.jar
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\ifxjdbc.jar
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\jta-1.1.jar
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\classmate-1.3.0.jar
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\jboss-logging-3.3.0.Final.jar
set CLASSPATH=%CLASSPATH%;D:\infx\work\Hibernate\lib5\antlr-2.7.7.jar
set CLASSPATH=%CLASSPATH%;.
D:\Infx\work\Hibernate>cat 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.informix.jdbc.IfxDriver
</property>
<property
name="connection.url">jdbc:informix-sqli://420ito:9088/stores7:INFORMIXSERVER=ids1210;user=informix;password=dummy;
</property>
<property
name="dialect">org.hibernate.dialect.InformixDialect
</property>
<property name="hibernate.show_sql">true
</property>
<property
name="current_session_context_class">thread
</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="State.hbm.xml"/>
</session-factory>
</hibernate-configuration>
D:\Infx\work\Hibernate>cat State.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class
name="State"
table="States">
<id
name="id"
column="id">
<generator class="increment"/>
</id>
<property
name="code"
column="code"/>
<property
name="sname"
column="sname"/>
<many-to-one
name="nextState"
cascade="all"
column="next_state_id"/>
</class>
</hibernate-mapping>
D:\Infx\work\Hibernate>cat HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
private static SessionFactory buildSessionFactory(){
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try {
return new
MetadataSources(registry).buildMetadata().buildSessionFactory();
}
catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
StandardServiceRegistryBuilder.destroy( registry );
throw new ExceptionInInitializerError(ex);
}
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
D:\Infx\work\Hibernate>cat create.java
import java.util.*;
import org.hibernate.*;
import javax.persistence.*;
public class create {
public static void main(String[] args) {
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.FINEST );
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.SEVERE );
Session Session = HibernateUtil.getSessionFactory().openSession();
Transaction Transaction = Session.beginTransaction();
State myState = new State();
myState.setcode(args[0]);
myState.setsname(args[1]);
Long stateId = (Long) Session.save(myState);
System.out.println("Stated added: "+myState.getcode()+", "+myState.getsname() );
Transaction.commit();
Session.close();
// Shutting down the application
HibernateUtil.shutdown();
}
}
D:\Infx\work\Hibernate>cat list.java
import java.util.*;
import org.hibernate.*;
import javax.persistence.*;
public class list {
public static void main(String[] args) {
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.FINEST );
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.SEVERE );
Session newSession = HibernateUtil.getSessionFactory().openSession();
Transaction newTransaction = newSession.beginTransaction();
List states = newSession.createQuery("from State order by id asc").list();
for ( Iterator iter = states.iterator();
iter.hasNext(); ) {
State state = (State) iter.next();
System.out.println(state.getcode() +", " + state.getsname() );
}
newTransaction.commit();
newSession.close();
HibernateUtil.shutdown();
}
}
D:\Infx\work\Hibernate>
create.java will insert a new row, and list.java will select from the 'State' table:
D:\Infx\work\Hibernate>java com.informix.jdbc.Version
IBM Informix JDBC Driver Version 4.10.JC9
D:\Infx\work\Hibernate>javac create.java
D:\Infx\work\Hibernate>javac list.java
D:\Infx\work\Hibernate>java create test1 test2
Hibernate: select max(id) from States
Stated added: test1, test2
Hibernate: insert into States (code, sname, next_state_id, id) values (?, ?, ?, ?)
D:\Infx\work\Hibernate>java list
Hibernate: select state0_.id as id1_0_, state0_.code as code2_0_, state0_.sname as sname3_0_, state0_.next_state_id as next_sta4_0_ from States state0_ order by state0_.id asc
test, test
test, test
test1, test2
D:\Infx\work\Hibernate>
but I guess it shouldn't be much different than what you already have.
Thanks for trying to help me out. The issue got resolved after I removed this property from hibernate config file.
<property name="hbm2ddl.auto">update</property>

Hibernate, data is not inserting into table

I'm a newbie to hibernate. I'm trying to insert data into table. It's only creating the tables but not inserting the data into table. I'm not sure where I'm doing wrong.
Any help would be appreciable.
UserDetails:
package org.com.etown.onetoone;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
#Entity
public class UserDetails {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
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;
}
}
UserDetailsDao:
package org.com.etown.onetoone;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class UserDatailsDao {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserName("george");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
hibernate.cfg.xml:
<?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 settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/etowndb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">root</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL Dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQL92Dialect</property>
<!-- Disable the second level class -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-creat the database schema on startup -->
<property name="hbm2ddl.auto">update</property><!-- update,create -->
<!-- Names of the annotated entity class -->
<mapping class="org.com.etown.onetoone.UserDetails"/>
</session-factory>
</hibernate-configuration>
Console Error:
Oct 13, 2016 12:46:30 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.1.Final}
Oct 13, 2016 12:46:30 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Oct 13, 2016 12:46:30 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Oct 13, 2016 12:46:30 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Oct 13, 2016 12:46:30 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Oct 13, 2016 12:46:30 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/etowndb]
Oct 13, 2016 12:46:30 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=postgres, password=****}
Oct 13, 2016 12:46:30 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Oct 13, 2016 12:46:30 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Oct 13, 2016 12:46:30 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL92Dialect
Oct 13, 2016 12:46:31 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
Oct 13, 2016 12:46:31 PM org.hibernate.type.BasicTypeRegistry register
INFO: HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType#7ffeac8e
Oct 13, 2016 12:46:31 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#31c08b2e] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Oct 13, 2016 12:46:31 PM org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl processGetTableResults
INFO: HHH000262: Table not found: UserDetails
Oct 13, 2016 12:46:31 PM org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl processGetTableResults
INFO: HHH000262: Table not found: UserDetails
Hibernate: create table UserDetails (userid int4 not null, userName varchar(255), primary key (userid))
Oct 13, 2016 12:46:31 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: SQL Warning Code: 0, SQLState: 00000
Oct 13, 2016 12:46:31 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: CREATE TABLE / PRIMARY KEY will create implicit index "userdetails_pkey" for table "userdetails"
Hibernate: select nextval ('hibernate_sequence')
Change
#GeneratedValue(strategy = GenerationType.AUTO)
To
#GeneratedValue(strategy = GenerationType.IDENTITY)
I am not sure , but it will work I think.
Edit
AUTO Indicates that the persistence provider should pick an
appropriate strategy for the particular database.
IDENTITY Indicates that the persistence provider must assign primary
keys for the entity using database identity column.
SEQUENCE Indicates that the persistence provider must assign primary
keys for the entity using database sequence column.
TABLE Indicates that the persistence provider must assign primary keys
for the entity using an underlying database table to ensure
uniqueness. Refer to the API here
http://docs.oracle.com/javaee/5/api/javax/persistence/GenerationType.html

Table created but not visible in database while using hibernate

application wizard
SQL command prompt ---showing account locked because of repeated wrong passwords, which is working fine in application wizard.
Everything seems to be right even in log info it is showing the table is created and data is inserted on the same, but I am unable to see the table and data in database.Can anybody suggest the possible reason.
Database : Oracle 10g
Log Info
Jun 12, 2016 8:38:30 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
Jun 12, 2016 8:38:30 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jun 12, 2016 8:38:30 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jun 12, 2016 8:38:30 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jun 12, 2016 8:38:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Jun 12, 2016 8:38:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:#localhost:1521:XE]
Jun 12, 2016 8:38:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=system, password=****}
Jun 12, 2016 8:38:31 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jun 12, 2016 8:38:31 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Jun 12, 2016 8:38:32 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Hibernate: drop table UserDetails cascade constraints
Hibernate: create table UserDetails (userid number(10,0) not null, userName varchar2(255 char), primary key (userid))
Jun 12, 2016 8:38:33 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl#1c3146bc'
Hibernate: insert into UserDetails (userName, userid) values (?, ?)
hibernate.cfg.xml
<?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">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.username">system</property>
<property name="connection.password">diwakar</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</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">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="com.diwakar.dto.UserDetails"/>
</session-factory>
</hibernate-configuration>
UserDetails.java
package com.diwakar.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 com.diwakar;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.diwakar.dto.UserDetails;
public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserid(1);
user.setUserName("Diwakar");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}

Hibernate working with queries

Started to learn hibernate. Doing everything by tutorial, but when I try to do simple select, nothing happens. Сan't understand what the problem is.
Logs:
мар 28, 2016 12:54:44 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.1.0.Final}
мар 28, 2016 12:54:44 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
мар 28, 2016 12:54:44 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
мар 28, 2016 12:54:45 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
мар 28, 2016 12:54:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
мар 28, 2016 12:54:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/taskboard]
мар 28, 2016 12:54:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
мар 28, 2016 12:54:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
мар 28, 2016 12:54:45 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
мар 28, 2016 12:54:45 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
мар 28, 2016 12:54:45 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.2.4.Final
мар 28, 2016 12:54:45 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/taskboard]
User.java
#Entity
#Table(name="Users")
public class User {
#Id
#Column(name="id_user")
private Long id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="login")
private String login;
#Column(name="password")
private String password;
}//get&set
Main.java
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
List<User> users = null;
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(User.class);
users = criteria.list();
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
sessionFactory.close();
}
for (User user: users) {
System.out.println(user.toString());
}
hibernate.cfg.xml
<?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>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/taskboard</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="User" />
</session-factory>
</hibernate-configuration>
HibernateUtil.java
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
static {
Configuration cfg = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties());
sessionFactory = cfg.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
As far as I remember, the newer version of hibernate do not support <mapping class= .../> in the hibernate configuration file any longer.
Can you remove that and instead try with
cfg.addAnnotatedClass(User.class) in your HibernateUtil static block.
On a different note, you may want to consider using the latest approach of building the sessionFactory as Configuration way is deprecated. Refer to Native Bootstrapping section for more information.
May be nothing in data base for Users table.First Insert some data. Then check.

Check user exists in database using hibernate

I am new in hibernate
I have a UserDAO class and a method to determine whether user exists in a specific table or not.
This is my users table in hb3 database:
And this is my class:
public static void main(String[] args) {
System.out.println(userExistsinDB("ABC"));
}
public static boolean userExistsinDB(String username) {
String queryStr = "Select * from users where username=" + username; // since username is unique
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createSQLQuery(queryStr);
System.out.println(query.getFirstResult());
session.getTransaction().commit();
session.close();
sessionFactory.close();
return false;
}
But the result is null in query.getFirstResult() , Why?
I have ABC username in users table.
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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hb3</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">2323</property>
<property name="hibernate.show_sql">true</property>
<mapping class="sajjad.htlo.User"/>
</session-factory>
</hibernate-configuration>
Result:
Feb 20, 2015 1:19:23 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Feb 20, 2015 1:19:23 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
Feb 20, 2015 1:19:23 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 20, 2015 1:19:23 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Feb 20, 2015 1:19:23 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Feb 20, 2015 1:19:23 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Feb 20, 2015 1:19:23 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Feb 20, 2015 1:19:23 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Feb 20, 2015 1:19:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Feb 20, 2015 1:19:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hb3]
Feb 20, 2015 1:19:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Feb 20, 2015 1:19:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Feb 20, 2015 1:19:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Feb 20, 2015 1:19:23 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Feb 20, 2015 1:19:23 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Feb 20, 2015 1:19:23 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
null
Feb 20, 2015 1:19:24 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/hb3]
false
Try this:
org.hibernate.Query query = session.createQuery("from users where username = :username");
query.setParameter("username", username);
query.uniqueResult();
You should use parameterized query. It returns null because string literals should be enclosed by quote notation.

Categories

Resources