null pointer exception while creating session factory - java

I am getting null pointer exception at the line
SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ;
any suggestion what might be causing it ??
error log says this :
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:214)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1797)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1755)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
at com.hussi.model.Main.main(Main.java:15)
my Main class File :
package com.hussi.model;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args)
{
User user = new User();
user.setUsername("hussi");
user.setPassword("maria");
SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ;
Session session = sesionFactory.openSession();
Transaction tr = session.beginTransaction();
session.save(user);
session.flush();
session.close();
}
}
my model file
package com.hussi.model;
public class User
{
int user_id;
String username;
String password;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString()
{
return "username==>"+this.username+" : password==>"+this.password;
}
}
my user.hbm.xml file
<?xml version="1.0"?>
<!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.hussi.model.User" table="users">
<id name="user_id" type="int" column="user_id">
<generator class="increment" />
</id>
<property name="username">
<column name="username"/>
</property>
<property name="password">
<column name="password"/>
</property>
</class>
</hibernate-mapping>
my hibernate configuration file : 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">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc.mysql://localhost:3306/my_hibernate_1</property>
<property name="connection.username">root</property>
<property name="connecttion.password">root</property>
<!-- Database connection settings -->
<property name="connection.pool_size">1</property>
<!-- MySql Dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>

You have given wrong url
below is correct one
jdbc:mysql://localhost:3306/my_hibernate_1
Just replaced jdbc.mysql with jdbc:mysql

Try changing the hibernate config connection.url property to jdbc:myql

Related

i am Getting org.hibernate.InvalidMappingException: Unable to read XML while running simple hibernate project

I'm running my first hibernate project which saves user information such as id,name and address into mysql database
This is my error log
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.InvalidMappingException: Unable to read XML
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:109)
at org.hibernate.cfg.Configuration.add(Configuration.java:490)
at org.hibernate.cfg.Configuration.add(Configuration.java:486)
at org.hibernate.cfg.Configuration.add(Configuration.java:659)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:742)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2197)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2169)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2149)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2102)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2017)
at mypack.DataInsertion.insertInfo(DataInsertion.java:18)
at mypack.DataInsertion.main(DataInsertion.java:11)
Caused by: org.dom4j.DocumentException: Error on line 3 of document : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.internal.util.xml.MappingReader.readMappingDocument(MappingReader.java:78)
... 11 more
hibernate.cfg.xml (Configuration 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>
<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibdb</property>
<property name="connection.user">root</property>
<property name="connection.password">admin</property>
<!-- Related to the connection END -->
<!-- Related to the hibernate properties START -->
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Related to the hibernate properties END -->
<!-- List of XML mapping files -->
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
user.hbm.xml (Mapping xml)
<!-- Mapping File to POJO Class -->
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="mypack.DataProvider" table="user_info">
<id name="user_id" column="table_id">
<generator class="assigned"/>
</id>
<property name="user_name" column = "name" />
<property name="user_address" column = "address" />
</class>
</hibernate-mapping>
DataProvider.java (POJO class)
//POJO Class
package mypack;
public class DataProvider {
private int user_id;
private String user_name;
private String user_address;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
}
DataInsertion.java (Implentation java class)
package mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DataInsertion {
public static void main(String[] args) {
new DataInsertion().insertInfo();
}
public void insertInfo()
{
Configuration con = new Configuration(); //interation with hib
con.configure("hibernate.cfg.xml"); //registering to xml
SessionFactory SF = con.buildSessionFactory(); //creating session
Session session = SF.openSession(); //opening new session
DataProvider provider = new DataProvider();
provider.setUser_id(1);
provider.setUser_name("Goutham");
provider.setUser_address("Hunsur");
Transaction TR = session.beginTransaction();
session.save(provider);
System.out.println("Object saved successfully");
TR.commit(); //saving transaction
session.close();
SF.close();
}
}
Please advise me,,,
Thanks.
Try removing the comment line and blank line before the first tag in user.hbm.xml

Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection using mySQL

I am trying to run a simple java project to see the working of hibernate but when i am executing my code it gives a hibernate exception, i am using mysql 5.6 and eclipse neon,i even checked for grant access and everything seems to be fine, please help Here is the code:
main.java
package com.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session = null;
SessionFactory sessionFactory= null;
//create sessionFactory
sessionFactory= new Configuration().configure().buildSessionFactory();
// create Session
session=sessionFactory.openSession();
// create and begin transaction
Transaction t = session.beginTransaction();
//create contact object and set values to the object
Contact contact = new Contact();
contact.setId(101);
contact.setFirstName("Dina");
contact.setLastName("adams");
contact.setEmailID("dina.adams#gmail.com");
// insert record by saving session
session.save(contact);
session.flush();
// commit transaction
t.commit();
//close the session
session.close();
}
}
contact.java
package com.demo;
public class Contact {
//properties
private String firstName;
private String lastName;
private String emailID;
private int id;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailID() {
return emailID;
}
public void setEmailID(String emailID) {
this.emailID = emailID;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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.url">jdbc:mysql://localhost:3306/emp</property>
<property name="hibernate.connection.usename">rajesh</property>
<property name="hibernate.connection.password">Nepal123</property>
<property name="hibernate.connection.poolsize">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping file -->
<mapping resource="Contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
contact.hbm.xml
<?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.demo.Contact" table="Contact">
<id column= "ID" name="id" type= "int" >
<generator class = "assigned"></generator>
</id>
<property name = "firstName">
<column name="FIRST NAME"></column>
</property>
<property name="lastName">
<column name="LAST NAME"></column>
</property>
<property name="emailID">
<column name ="EMAIL ID"></column>
</property>
</class>
</hibernate-mapping>
error message:-
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:426)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at com.demo.Main.main(Main.java:25)
Caused by: java.sql.SQLException: Access denied for user ''#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:875)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1712)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1228)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2253)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2284)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2083)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:806)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:410)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:328)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:423)
... 5 more
Check out this tag:
<property name="hibernate.connection.usename">rajesh</property>
the name should be hibernate.connection.username instead of hibernate.connection.usename.

I can't get get the SessionFactory in Hibernate 5.1.0. My code breaks in the line while getting the SessionFactory obj

Image
ERROR:
1) AdminModel.java - Model class.
2) HibernateUtil.java facilitates the Hibernate DB conn.
3) AdminDAO.java - u guyz know what these are...I'll save the pain to explain...and oh yes...m already through days of pain with this bug ...trynna debug...i've got deadlines to meet... if u guyz could help me it'd be a matter of great deal...
public class AdminModel {
private int adminID;
private String username;
private String password;
public int getAdminID() {
return adminID;
}
public void setAdminID(int adminID) {
this.adminID = adminID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
HibernateUtil.java
public class HibernateUtil {
public static SessionFactory sessionFactory;
static {
try {
/* File f=new File("O:/#workspace/#eclipse/ekatabookstore.com/src/hibernate.cfg.xml");
sessionFactory =new Configuration().configure(f).buildSessionFactory();
*/
/****OR****/
String hibernatePropsFilePath = "O:/#workspace/#eclipse/ekatabookstore.com/src/hibernate.cfg.xml";
File hibernatePropsFile = new File(hibernatePropsFilePath);
Configuration configuration = new Configuration();
configuration.configure(hibernatePropsFile);
configuration.addResource("ekatabookstore.hbm.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
//throw new ExceptionInInitializerError(ex);
}
}
public static Session openSession() {
return HibernateUtil.sessionFactory.openSession();
//return sessionFactory.getCurrentSession();
}
}
AdminDAO.java
public AdminDAO(AdminModel adminUserObj) {
public void createAdmin() {
/*
* CRUD operation of HIBERNATE C-->Create SessionFactory Object is a
* heavy object and takes up huge resources, so it is better to create
* only one object and share it where needed.
*/
SessionFactory sessionFactoryObj = HibernateUtil.sessionFactory;
// System.out.println(sessionFactoryObj.getClass().getName());
Session session = sessionFactoryObj.openSession();
session.beginTransaction();// Transaction Started
session.save(adminObj);// SAVED
session.getTransaction().commit();// Transaction Ended
System.out.println("!!!SUCCESSFUL CREATE!!!");
session.close();// CLOSE session resource of Hibernate
Notification.notificationMsg = "ADMIN CREATE - SUCCESSFUL!";
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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://localhost:3306/ekatabookstoreDB</property>
<property name="connection.username">xyz</property>
<property name="connection.password">xyz</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</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.internal.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> -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="ekatabookstore.hbm.xml" />
</session-factory>
</hibernate-configuration>
hbn.properties
hiberNateCfgFileName=hibernate.cfg.xml
ekatabookstore.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">
<hibernate-mapping>
<class name="com.ekatabookstore.layer.service.model.AdminModel" table="admin">
<id name="adminID" type="integer" column="id_admin">
<generator class="assigned" />
</id>
<property name="username" type="string" column="username" not-null="true" />
<property name="password" type="string" column="password" not-null="true" />
</class>
</hibernate-mapping>
If you are using spring then, Add autowire on sessionfactory or get it from application context. You can use following code
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware{
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
#Override
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
context = ac;
}
}
You can use this class anywhere in your code like
ApplicationContextProvider.getApplicationContext().getBean("sessionFactory");
Please try the following code for creating sessionfactory
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
StandardServiceRegistryBuilder.destroy( registry );
}
Hope this helps.

UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0)

In the code below when I try to execute Main.java I am getting exception:
Exception in thread "main" org.hibernate.UnknownEntityTypeException: Unable to locate persister: com.np.vta.test.pojo.Users
at org.hibernate.internal.SessionFactoryImpl.locateEntityPersister(SessionFactoryImpl.java:792)
at org.hibernate.internal.SessionImpl.locateEntityPersister(SessionImpl.java:2637)
at org.hibernate.internal.SessionImpl.access$2500(SessionImpl.java:164)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2575)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.<init>(SessionImpl.java:2562)
at org.hibernate.internal.SessionImpl.byId(SessionImpl.java:1044)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955)
at com.app.test.Main.main(Main.java:20)
but if I do uncomment cfg.addClass( Users.class ).addResource( "com/np/vta/test/pojo/Users.hbm.xml" ); then the code works fine.
Why it is not reading the <mapping> from hibernate.cfg.xml?
Project setup
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">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root#123321</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.1.90:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/np/vta/test/pojo/Users.hbm.xml" class="com.np.vta.test.pojo.Users" />
</session-factory>
</hibernate-configuration>
Users.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 24 Aug, 2015 3:57:45 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.np.vta.test.pojo.Users" table="tomcat_users">
<id name="userName" type="java.lang.String">
<column name="user_name" />
<generator class="assigned" />
</id>
<property name="password" type="java.lang.String">
<column name="password" />
</property>
</class>
</hibernate-mapping>
Users.java
package com.np.vta.test.pojo;
import java.io.Serializable;
public class Users implements Serializable
{
private static final long serialVersionUID = 7855937172997134350L;
private String userName;
private String password;
public Users()
{
}
// getter and setters
}
Main.java
package com.app.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.np.vta.test.pojo.Users;
public class Main
{
public static void main( String[] args )
{
Configuration cfg = new Configuration();
cfg.configure( "hibernate.cfg.xml" );
// cfg.addClass( Users.class ).addResource( "com/np/vta/test/pojo/Users.hbm.xml" );
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder().applySettings( cfg.getProperties() );
SessionFactory sessionFactory = cfg.buildSessionFactory( registryBuilder.build() );
Session session = sessionFactory.openSession();
Users users = session.get( Users.class, "anand" );
System.out.println( users );
}
}
Don't use Configuration with StandardServiceRegistryBuilder, Configuration is considered deprecated, but instead make the bootstrapping as mentioned in the hibernate 5 documentation, I had the same problem and this fixed it.
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure( "org/hibernate/example/MyCfg.xml" )
.build();
Metadata metadata = new MetadataSources( standardRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClassName( "org.hibernate.example.Customer" )
.addResource( "org/hibernate/example/Order.hbm.xml" )
.addResource( "org/hibernate/example/Product.orm.xml" )
.getMetadataBuilder()
.applyImplicitNamingStrategy( ImplicitNamingStrategyJpaCompliantImpl.INSTANCE )
.build();
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder()
.applyBeanManager( getBeanManagerFromSomewhere() )
.build();
for further details , check the documentation
Try adding configure() method at the end.
StandardServiceRegistryBuilder registryBuilder = new
StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).configure();
This same error can also be caused by a missing or incorrect context:component-scan.

org.postgresql.util.PSQLException: ERROR: the relation"clienti_id_seq" does not exist

I am trying to learn hibernate framework with making a simple program that push a class Cliente into a table on postgres, The error that returns is as follow:
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Caused by: org.postgresql.util.PSQLException: ERROR: the relation "clienti_id_seq" does not exist
This is my database by PGAdmin (sorry for imgur i can't upload picture directly) http://i.imgur.com/Fz9o1fR.png?1
This is the class Cliente
public class Cliente {
private long clienteId;
private String clienteNome;
private String clienteCognome;
private String clienteTelefono;
private String clienteMail;
private String clientePermesso;
private long clienteCommessa;
public long getClienteId() {
return clienteId;
}
public void setClienteId(long clienteId) {
this.clienteId = clienteId;
}
public String getClienteNome() {
return clienteNome;
}
public void setClienteNome(String clienteNome) {
this.clienteNome = clienteNome;
}
public String getClienteCognome() {
return clienteCognome;
}
public void setClienteCognome(String clienteCognome) {
this.clienteCognome = clienteCognome;
}
public String getClienteTelefono() {
return clienteTelefono;
}
public void setClienteTelefono(String clienteTelefono) {
this.clienteTelefono = clienteTelefono;
}
public String getClienteMail() {
return clienteMail;
}
public void setClienteMail(String clienteMail) {
this.clienteMail = clienteMail;
}
public String getClientePermesso() {
return clientePermesso;
}
public void setClientePermesso(String clientePermesso) {
this.clientePermesso = clientePermesso;
}
public long getClienteCommessa() {
return clienteCommessa;
}
public void setClienteCommessa(long clienteNome) {
this.clienteCommessa = clienteCommessa;
}
}
This is my mapping file
<hibernate-mapping>
<class name="beans.Cliente" table="Clienti">
<id name="clienteId" type="integer" column="id" >
<generator class="sequence">
<param name="sequence">CLIENTI_ID_seq</param>
</generator>
</id>
<property name="clienteNome" column="nome" type="string">
</property>
<property name="clienteCognome" column="cognome" type="string">
</property>
<property name="clienteTelefono" column="telefono" type="string">
</property>
<property name="clienteMail" column="mail" type="string">
</property>
<property name="clientePermesso" column="permesso" type="string">
</property>
<property name="clienteCommessa" column="commessa" type="string">
</property>
</class>
</hibernate-mapping>
This is the hibernate cfg.xml file, the information about url pass and user are correct
<?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.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql:postgres</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/Georilievi</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">Fabio1990</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="Clienti.hbm.xml"/>
</session-factory>
</hibernate-configuration>
This is the main file, here i create an istance of Cliente, and try to push in the postgres database
package main;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import beans.Cliente;
public class Main {
public static void main(String [] args){
// Create a configuration instance
Configuration configuration = new Configuration();
// Provide configuration file
configuration.configure("hibernate.cfg.xml");
// Build a SessionFactory
SessionFactory factory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build());
// Get current session, current session is already associated with Thread
Session session = factory.getCurrentSession();
// Begin transaction
session.getTransaction().begin();
Cliente cliente = new Cliente();
cliente.setClienteNome("Fabio");
cliente.setClienteCognome("Tramontana");
cliente.setClienteTelefono("3343052346");
cliente.setClienteMail("info.tramontanafabio#gmail.com");
cliente.setClientePermesso("admin");
cliente.setClienteCommessa(0);
// Save*/
session.save(cliente);
// Commit, calling of commit will cause save an instance of employee
session.getTransaction().commit();
}
}
thanks all of you for helping me, i don't understand the error, i think it is in the declaration of the generator.
Please try changing the generator class from sequence to identity and see. I guess the issue is the auto generation of IDs.
See these links:
http://www.roseindia.net/hibernate/hibernateidgeneratorelement.shtml
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-property

Categories

Resources