Exception in Hibernate console application - java

I have a simple console application built using Hibernate. It throws an exception when I run it, and I don't know what the problem is.
My code is:
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.classic.Session;
import org.hibernate.tool.hbm2ddl.SchemaExport;
public class TestEmployee {
public static void main(String[] args) {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Employee.class);
config.configure("hibernate.cfg.xml");
new SchemaExport(config).create(true, true);
SessionFactory factory = config.buildSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
Employee tom = new Employee();
mehdi.setEmpId(100);
mehdi.setEmpName("Tom Hani");
session.save(mehdi);
session.getTransaction().commit();
}
}
The exception is:
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:685)
at com.Hibernate.chapter1.TestEmployee.main(TestEmployee.java:20)

I suspect your Hibernate configuration is not proper for current session.
Either you are missing hibernate.current_session_context config or using below property in your hibernate configuration
<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocal‌​SessionContext</property>
instate please use below property
<property name="hibernate.current_session_context_class">thread</property>
For more information on Hibernate current session please visit this link.

Related

java hibernate - cannot find beginTransaction and createQuery

I got a problem with the two hibernate methods mentioned in the title, beginTransaction() and createQuery(). Java gives me the cannot find symbol error
This is how I start my session
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
public static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
}
and this is how I use the two methods
SessionFactory session = HibernateUtil.createSessionFactory();
Transaction tx = null;
Users user = null;
try {
tx = session.beginTransaction();
tx.begin();
Query query = session.createQuery("FROM USERS WHERE USERNAME='"+userId+"'");
user = (Users)query.uniqueResult();
tx.commit();
}
I'm fairly unfamiliar with hibernate and I don't understand why this is happening. I set up my xml config file properly. Netbeans supposedly added all the necessary libraries and I still get the error
You have to change this line :
SessionFactory session = HibernateUtil.createSessionFactory();
to
Session session = HibernateUtil.createSessionFactory().openSession();
Because SessionFactory interface does not implement the SharedSessionContract interface which include both
getTransaction()
createQuery(String string)
methods like Sessioninterface does.
And it is good practice to use parameter binding instead of using string concatenation.
Query query = session.createQuery("FROM USERS WHERE USERNAME= :userName")
.setParameter("userName",userId);

Connecting to PostgreSQL-server with Hibernate from IntelliJ

I am attempting to persist data to a PostgreSQL-database via Hibernate, have put in my user/pass, checked that it's working, made a db and some tables.
When I compile, I get an error
org.postgresql.util.PSQLException: The server
requested password-based authentication, but no password was provided.
I'm using IntelliJ Ultimate 2017.1 and have tried using both the supplied pg driver and 42.00 as external library.
I've had it working in previous versions, but never seen this one before. Must admit I'm not very good at this.
Basically, my defined password does not get correctly passed on to the server. It seems like it recognized my username. I've temporarily evaded this problem by modifying my pg_hba.conf file to trust local connections without password, but I am going to persist the data on an online server, so I'm gonna need a better fix.
The driver has a standard URL template that looks like this:
jdbc:postgresql:{database::postgres}[\?<&,user={user:param},password={password:param},{:identifier}={:param}>]
Here is my hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:postgresql://localhost:5432/gigahertz</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<mapping class="no.hvl.dat101.gigahertz.ReservationJPA"/>
<!-- <property name="connection.username"/> -->
<!-- <property name="connection.password"/> -->
<!-- DB schema will be updated if needed -->
<!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
Here is my generated Main-class
package no.hvl.dat101.gigahertz;
import org.hibernate.HibernateException;
import org.hibernate.Metamodel;
import org.hibernate.query.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import javax.persistence.metamodel.EntityType;
import java.util.Map;
/**
*/
public class Main {
private static final SessionFactory ourSessionFactory;
static {
try {
Configuration configuration = new Configuration();
configuration.configure();
ourSessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}
public static void main(final String[] args) throws Exception {
final Session session = getSession();
try {
System.out.println("querying all the managed entities...");
final Metamodel metamodel = session.getSessionFactory().getMetamodel();
for (EntityType<?> entityType : metamodel.getEntities()) {
final String entityName = entityType.getName();
final Query query = session.createQuery("from " + entityName);
System.out.println("executing: " + query.getQueryString());
for (Object o : query.list()) {
System.out.println(" " + o);
}
}
} finally {
session.close();
}
}
}
Any advice appreciated!
The solution to this was to add the parameters in the try block in main in the form configuration.setProperty("hibernate.connection.username","u‌​sername) etc.
For some reason, the login details were not passed correctly by IntelliJ to the server.

Exception in thread "main" java.util.ServiceConfigurationError [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
This error is occuring with Hibernate 3.2 and resolved by using ServiceRegistryBuilder
This is my code:
public class HibernateTest {
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("Sam");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
Error:
Exception in thread "main" java.util.ServiceConfigurationError: org.hibernate.boot.registry.selector.StrategyRegistrationProvider: Provider org.hibernate.cache.infinispan.StrategyRegistrationProviderImpl not found
at java.util.ServiceLoader.fail(ServiceLoader.java:231)
at java.util.ServiceLoader.access$300(ServiceLoader.java:181)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:365)
at java.util.ServiceLoader$1.next(ServiceLoader.java:445)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.loadJavaServices(ClassLoaderServiceImpl.java:340)
at org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder.buildSelector(StrategySelectorBuilder.java:162)
at org.hibernate.boot.registry.BootstrapServiceRegistryBuilder.build(BootstrapServiceRegistryBuilder.java:222)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:119)
This was the error while executing the hibernate framework with wrong api's.
This problem was resolved by changing my code like this:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateTest {
private static SessionFactory sessionFactory;
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("Sam");
if (sessionFactory == null) {
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
This was the code.
You have different version of Hibernate. Probably 4 and above. According to guideline you should use following syntax
http://www.codejava.net/frameworks/hibernate/building-hibernate-sessionfactory-from-service-registry

How can I create a Hibernate session without hiberante.cfg.xml file?

This is my first time using Hiberante.
I am trying to create a Hibernate session within my application using the following:
Session session = HiberanteUtil.getSessionFactory().openSession();
It gives me this error:
org.hibernate.HibernateException: /hibernate.cfg.xml not found
However I do not have a hibernate.cfg.xml file within my project.
How can I create a session without having this file?
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import com.concretepage.persistence.User;
public class HibernateUtil {
private static final SessionFactory concreteSessionFactory;
static {
try {
Properties prop= new Properties();
prop.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
prop.setProperty("hibernate.connection.username", "root");
prop.setProperty("hibernate.connection.password", "");
prop.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
concreteSessionFactory = new AnnotationConfiguration()
.addPackage("com.concretepage.persistence")
.addProperties(prop)
.addAnnotatedClass(User.class)
.buildSessionFactory();
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static Session getSession()
throws HibernateException {
return concreteSessionFactory.openSession();
}
public static void main(String... args){
Session session=getSession();
session.beginTransaction();
User user=(User)session.get(User.class, new Integer(1));
System.out.println(user.getName());
session.close();
}
}
The simples way to configure Hibernate 4 or Hibernate 5
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Hibernate reads a configuration from hibernate.cfg.xml and hibernate.properties.
You shouldn't call configure(), if you don't want to read hibernate.cfg.xml. With adding an annotated class
SessionFactory sessionFactory = new Configuration()
.addAnnotatedClass(User.class).buildSessionFactory();

compiler error in hibernate 5.0.1

I am learning hibernate, I have added all the required jars, but still am getting a compiler error saying
Configuration.configure cannot be resolved to a type.
My jar list:
Anyone have idea how to resolve this?
package org.ramya.hibernate;
import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;
import org.ramya.dto.UserDetails;
public class HibernateTest {
public static void main (String args[])
{
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("First user");
SessionFactory sessionFactory = new Configuration.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
}
}
You missed the parentheses () when instantiating the Configuration object.
It should be:
new Configuration().configure()
Try to use This,
SessionFactory sf;
ServiceRegistry sr;
Configuration cfg=new Configuration().configure();
sr=new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
sf=cfg.buildSessionFactory(sr);
Instead of ,
SessionFactory sessionFactory = new Configuration.configure().buildSessionFactory();
Since "buildSessionFactory()" has been deprecated over hibernate 3.5
And try to use latest version of hibernate as much as possible.
Please check this link for Details:-
Deprecated Buildsessionfactory

Categories