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
Related
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);
For teaching purposes, I am creating Hibernate console applications. Since Hibernate is quite complex, I want to be sure that I handle the initialization, exceptions, and shutdown correctly. The examples that I have found are not optimal in my opinion. (Official Hibernate examples use test cases.)
I have HibernateUtil for initialization and shutdown of Hibernate.
package com.zetcode.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class HibernateUtil {
private SessionFactory sessionFactory;
public HibernateUtil() {
createSessionFactory();
}
private void createSessionFactory() {
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
// try {
// sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
// } catch (Exception e) {
// The registry would be destroyed by the SessionFactory, //but we had trouble building the SessionFactory
// so destroy it manually.
// StandardServiceRegistryBuilder.destroy(registry);
}
}
public SessionFactory getSessionFactory() {
// if (sessionFactory == null) {
// createSessionFactory();
// }
return sessionFactory;
}
public void shutdown() {
getSessionFactory().close();
}
}
Here is a console Java application:
package com.zetcode.main;
import com.zetcode.bean.Continent;
import com.zetcode.bean.Country;
import com.zetcode.util.HibernateUtil;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class Application {
public static void main(String[] args) {
HibernateUtil hutil = new HibernateUtil();
SessionFactory sessionFactory = hutil.getSessionFactory();
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
Continent europe = new Continent("Europe");
Continent asia = new Continent("Asia");
Country svk = new Country("Slovakia");
Country hun = new Country("Hungary");
Set<Country> europeCountries = new HashSet<>();
europeCountries.add(svk);
europeCountries.add(hun);
europe.setCountries(europeCountries);
Country chi = new Country("China");
Country afg = new Country("Afganistan");
Set<Country> asiaCountries = new HashSet<>();
asiaCountries.add(chi);
asiaCountries.add(afg);
asia.setCountries(asiaCountries);
session.save(europe);
session.save(asia);
// moved
//session.getTransaction().commit();
Query query = session.createQuery("SELECT c FROM Country c");
List<Country> countries = query.getResultList();
countries.stream().forEach((x) -> System.out.println(x));
Query query2 = session.createQuery("SELECT c FROM Continent c");
List<Continent> continents = query2.getResultList();
continents.stream().forEach((x) -> System.out.println(x));
session.getTransaction().commit();
} finally {
hutil.shutdown();
}
}
}
The example works OK. But, is this code correct? I am using Hibernate 5.2.
Edit I have incorporated the suggestions from the comments into the code.
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();
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
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.