After changing JDBC to hibernate the application runs very slow - java

Previously I used JDBC in my application and it was running very fast, but I have modified it to use Hibernate which made it too slow, especially when it needs to open a page that has a dropdown box in it. It takes much longer in compare to JDBC, to open this kind of pages.
If I try to access a table with foreign keys it takes much longer.
My server is GlassFish and I am usingfollowing version of hibernate.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.10.Final</version>
<type>jar</type>
</dependency>
The questions are why is it to slow in compare to JDBC and do I need to have the following lin before each session.beginTransaction() ?
session = HibernateUtil.getSessionFactory().openSession();
Take the following one as an example, it has a dropdown box that need to be populated once the page is opened.
HibernateUtil.java
package com.myproject.util;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static SessionFactory configureSessionFactory() {
try {
System.out.println("1");
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new
ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
System.out.println("2");
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
System.out.println("3");
return sessionFactory;
} catch (HibernateException e) {
System.out.append("** Exception in SessionFactory **");
e.printStackTrace();
}
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return configureSessionFactory();
}
}
MyClassModel.java
public class MyClassModel extends HibernateUtil {
private Session session;
public Map populatedropdownList() {
Map map = new HashMap();
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<MyListResult> temp = null;
try{
temp = retrieveItems();
System.err.println("size:" + temp.size());
for(int i=0;i<temp.size();i++){
map.put(temp.get(i).getId(),temp.get(i).getName());
}
session.getTransaction().commit();
session.close();
return map;
}catch(Exception e){
e.printStackTrace();
}
return map;
}
private List <MyListResult> retrieveItems(){
Criteria criteria = session.createCriteria(MyTable.class, "MyTable");
ProjectionList pl = Projections.projectionList();
pl.add(Projections.property("MyTable.id").as("id"));
pl.add(Projections.property("MyTable.name").as("name"));
criteria.setProjection(pl);
criteria.setResultTransformer(new
AliasToBeanResultTransformer(MyListResult.class));
return criteria.list();
}
MyListResult.java
public class MyListResult implements Serializable {
private int id;
private String Name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
}
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/MyDatabase
</property>
<property name="connection.username">root</property>
<property name="connection.password"></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.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">update</property>
<mapping class="com.MyProject.MyTable" />
</session-factory>
</hibernate-configuration>
Console is as following
INFO: in myform
INFO: 1
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
INFO: HHH000041: Configured SessionFactory: null
INFO: 2
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
INFO: HHH000115: Hibernate connection pool size: 1
INFO: HHH000006: Autocommit mode: false
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL
[jdbc:mysql://localhost:3306/MyDatabase]
INFO: HHH000046: Connection properties: {user=root, password=****}
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
INFO: HHH000397: Using ASTQueryTranslatorFactory
INFO: HHH000228: Running hbm2ddl schema update
INFO: HHH000102: Fetching database metadata
INFO: HHH000396: Updating schema
INFO: HHH000261: Table found: MyDatabase.MyTable
INFO: HHH000037: Columns: [id, name, age, xx, yy]
INFO: HHH000126: Indexes: [primary]
INFO: HHH000232: Schema update complete
INFO: Hibernate: select this_.id as y0_, this_.name as y1_ from MyTable this_
SEVERE: size:4

Usually in the application you shouldn't build the session factory each time when you need the session. That's what actually needed by application to use the hibernate. If you want to manage the session manually then you write the HibernateUtil making it singleton. Initially, build the session factory in the static initializer block
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<>();
private static SessionFactory sessionFactory;
static {
try {
sessionFactory = configureSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateUtil() {
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session getSession() throws HibernateException {
Session session = threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession() : null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
sessionFactory = configureSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
think that's enough addition to your code to run your application.

While I don't have any direct experience with Hibernate, I do with NHibernate, which is modeled after the Java version, so this should still be correct...
Building up the SessionFactory takes time, all the more so since, if I'm reading the configuration right, you're having it check for schema changes between your models and the database when it does start.
What you should do instead is create the SessionFactory once on startup (or upon the first use of data access, depending on when you want to pay the cost of setting up Hibernate) and use that through the lifetime of your app.
What I tend to do is something roughly like this (rough psuedocode, since my Java is rusty):
Session getSession()
{
if(sessionFactory == null)
buildSessionFactory()
return sessionFactory.OpenSession()
}
(Of course this doesn't take into account any possible race conditions with threading). This should hopefully see a rather large performance boost. Keep in mind that ORMs are almost never as fast as hand-coded SQL due to the additional mapping layers, but it's a trade off between performance and ease of coding.

Related

I am trying to connect to a database that I created with java using hibernate. I am getting this error and I am not sure why

I am trying to connect to a database that I created with java in eclipse using hibernate. It is supposed to connect to the payroll database and insert records into the student table but I am getting this error! I inserted the jdbc connect and the other required jar files. I am not sure why it's not working. Please help.
Error:
Jul 14, 2022 2:34:10 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.5.3.Final
Jul 14, 2022 2:34:11 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/payroll]
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jul 14, 2022 2:34:11 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 3 (min=1)
Jul 14, 2022 2:34:11 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
Jul 14, 2022 2:34:11 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#304b9f1a] 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.
Hibernate:
select
student0_.id as id1_0_,
student0_.email as email2_0_,
student0_.first_name as first_na3_0_,
student0_.last_name as last_nam4_0_
from
student student0_
Hibernate:
select
student0_.id as id1_0_0_,
student0_.email as email2_0_0_,
student0_.first_name as first_na3_0_0_,
student0_.last_name as last_nam4_0_0_
from
student student0_
where
student0_.id=?
Exception in thread "main" java.lang.IllegalStateException: org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl#5eb97ced is closed
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.errorIfClosed(AbstractLogicalConnectionImplementor.java:37)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:137)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:276)
at org.hibernate.resource.jdbc.internal.AbstractLogicalConnectionImplementor.rollback(AbstractLogicalConnectionImplementor.java:121)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.rollback(JdbcResourceLocalTransactionCoordinatorImpl.java:304)
at org.hibernate.engine.transaction.internal.TransactionImpl.rollback(TransactionImpl.java:142)
at models.Student.get(Student.java:131)
at Driver.main(Driver.java:24)
Driver Class(driver.java)
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import models.Student;
public class Driver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu =new Student();//1,"Simone","Charles","#Home");
//stu.create();
List<Student> students=stu.readAll();
for(Student s: students) {
System.out.println(s.getFirstName());
}
Student s1=stu.get(4);
System.out.println(s1.getFirstName());
//sstu.delete(2);
//getCurrentSessionFromConfig();
}
public static Session getCurrentSessionFromConfig() {
// SessionFactory in Hibernate 5 example
Configuration config = new Configuration();
config.configure();
// local SessionFactory bean created
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
return session;
}
public static Session getCurrentSessionX() {
// Hibernate 5.4 SessionFactory example without XML
Map<String, String> settings = new HashMap<>();
settings.put("connection.driver_class", "com.mysql.jdbc.Driver");
settings.put("dialect", "org.hibernate.dialect.MySQL8Dialect");
settings.put("hibernate.connection.url",
"jdbc:mysql://localhost/hibernate_examples");
settings.put("hibernate.connection.username", "root");
settings.put("hibernate.connection.password", "");
settings.put("hibernate.current_session_context_class", "thread");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.format_sql", "true");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(settings).build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
// metadataSources.addAnnotatedClass(Player.class);
Metadata metadata = metadataSources.buildMetadata();
// here we build the SessionFactory (Hibernate 5.4)
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
Session session = sessionFactory.getCurrentSession();
return session;
}
}
Hibernate 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">
<!-- Version 8 MySQL hiberante-cfg.xml example for Hibernate 5 -->
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- property name="connection.driver_class">com.mysql.jdbc.Driver</property -->
<property name="connection.url">jdbc:mysql://localhost/payroll</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">3</property>
<!--property name="dialect">org.hibernate.dialect.MySQLDialect</property-->
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- mapping class="com.mcnz.jpa.examples.Player" / -->
<mapping class="models.Student" />
</session-factory>
</hibernate-configuration>
SessionBuilder File
package factories;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import models.Student;
public class SessionFactoryBuilder {
private static SessionFactory sessionFactory = null;
public static SessionFactory getSessionFactory () {
if(sessionFactory==null) {
try {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
sessionFactory = cfg.buildSessionFactory();
// session =sessionFactory.openSession();
/* sessionFactory =new
Configuration().configure("hibernate.cfg.xml").addAnnotatedClass
(Student.class).buildSessionFactory();
*/
}catch(RuntimeException e) {System.out.println(e.toString());}
}
return sessionFactory;
}
public static void closeSessionFactory () {
if(sessionFactory!=null) {
sessionFactory.close();
}
}
}
Student Class
package models;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;
import org.hibernate.Session;
import org.hibernate.Transaction;
import factories.SessionFactoryBuilder;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
int id;
#Column(name="first_name")
String firstName;
#Column(name="last_name")
String lastName;
#Column(name="email")
String email;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int id, String firstName, String lastName, String email) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void create() {
Session session =SessionFactoryBuilder.getSessionFactory().getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
//stu.setFirstName(firstName);
//stu.setLastName(lastName);
session.save(this);
transaction.commit();
session.close();
}
public List<Student> readAll(){
List<Student> studentList=new ArrayList<>();
Session session =SessionFactoryBuilder.getSessionFactory().getCurrentSession();
Transaction transaction= session.beginTransaction();
studentList=(List<Student>) session.createQuery("From Student").getResultList();
transaction.commit();
session.close();
return studentList;
}
public void delete(int id) {
Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
//session.delete(stu);
// Delete a persistent object
Student student = session.get(Student.class, id);
if (student != null) {
session.delete(student);
System.out.println("student deleted");
}
// Delete a transient object
/* Student student2 = new Student();
student2.setId(2);
session.delete(student2);
System.out.println("Student 2 is deleted");
*/
transaction.commit();
session.close();
}
public void update() {
Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession();
Transaction transaction= session.beginTransaction();
//Student stu=(Student) session.get(Student.class, this.id);
session.update(this);
transaction.commit();
session.close();
}
public Student get(int id) {
Student stu=null;
Transaction transaction=null;
try(Session session =SessionFactoryBuilder.getSessionFactory()
.getCurrentSession()){
transaction= session.beginTransaction();
stu=(Student) session.get(Student.class, id);
session.delete(stu);
transaction.commit();
}catch(Exception e) {
if(transaction!=null) {
transaction.rollback();
}
e.printStackTrace();
}
return stu;
}
}

using hibernate and jpa with springboot

I have a spring boot project. I put in my resource folder hibernate.cfg.xml file.
this is my hibernate.cfg.xml 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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">***</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/exportbatch?serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
</session-factory>
I have a hibernateUtil class used to instantiate a hibernate session.
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
// Create the SessionFactory from hibernate.cfg.xml
// return new Configuration().configure().buildSessionFactory();
return new AnnotationConfiguration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
// Close caches and connection pools
getSessionFactory().close();
}
}
In my application controller I have an endpoint in which I am requesting my mysql database.
#RequestMapping("/getbuildinginfo/{buildingid}")
public void getbuildinginfo(String buildingid)
Session session = null;
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String query = "select * from exportbatch.exportbatch";
SQLQuery sqlQuery = session.createSQLQuery(query);
List<Object[]> rows = sqlQuery.list();
HibernateUtil.shutdown();
This works fine the first time I run the project, but if I call the endpoint a second time, I am getting this exception:
org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]
Could someone help me with this ? why it works the first time? Is it a spring boot context problem? if yes how could I resolve it ?

Why does hibernate drops foreing key constraint before creating tables?

Here is my simple hibernate.cfg.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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/UserDB</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</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.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create-drop</property>
<!-- Mapping files -->
<mapping class="com.stackoverflow.model.Person" />
<mapping class="com.stackoverflow.model.Phone" />
</session-factory>
Here is simple Person entity:
#Entity(name = "Person")
public class Person {
#Id
#GeneratedValue
private Long id;
public Person() {
}
}
Here is simple Phone entity:
#Entity(name = "Phone")
public class Phone {
#Id
#GeneratedValue
private Long id;
#Column(name = "`number`")
private String number;
#ManyToOne(cascade=CascadeType.ALL,optional=false)
#JoinColumn(name = "person_id",
foreignKey = #ForeignKey(name = "PERSON_ID_FK")
)
private Person person;
public Phone() {
}
public Phone(String number) {
this.number = number;
}
public Long getId() {
return id;
}
public String getNumber() {
return number;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
Here is junit test class that tries to save this relationship into database:
public class TestManyToOne {
private static SessionFactory sessionFactory;
private Session session;
#BeforeClass
public static void setUp() throws Exception {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
.build();
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);
System.out.println("Exception\n" + e);
}
assertNotNull(sessionFactory);
}
#AfterClass
public static void tearDown() throws Exception {
sessionFactory.close();
}
#Before
public void beforeEach() {
session = sessionFactory.getCurrentSession();
session.beginTransaction();
}
#After
public void afterEach() {
session.getTransaction().commit();
session.close();
}
#Test
public void testSave() {
Person person = new Person();
Phone phone1 = new Phone("93283287832");
Phone phone2 = new Phone("0987654321");
phone1.setPerson(person);
phone2.setPerson(person);
session.save(phone1);
session.save(phone2);
}
}
It has only one #Test method called testSave. When I run it on just created database I get error :
Hibernate:
alter table Phone
drop
foreign key PERSON_ID_FK
апр 11, 2017 5:50:54 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess#6f2cfcc2] 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.
апр 11, 2017 5:50:54 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:62)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlString(SchemaDropperImpl.java:374)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applySqlStrings(SchemaDropperImpl.java:359)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.applyConstraintDropping(SchemaDropperImpl.java:331)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.dropFromMetadata(SchemaDropperImpl.java:230)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.performDrop(SchemaDropperImpl.java:154)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:126)
at org.hibernate.tool.schema.internal.SchemaDropperImpl.doDrop(SchemaDropperImpl.java:112)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:137)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:65)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:307)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:490)
at org.hibernate.boot.internal.MetadataImpl.buildSessionFactory(MetadataImpl.java:170)
at com.stackoverflow.dao.TestDao.setUp(TestDao.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
Hibernate:
drop table if exists hibernate_sequence
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'userdb.phone' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:734)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:49)
... 30 more
In error this line is important:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'userdb.phone' doesn't exist
How to tell hibernate do not drop foreign key constraint before creating tables?
Thank you.
I didn't believe it but the problem was that connection pool size was set to 1. After I set it to ten
<property name="connection.pool_size">10</property>
junit test runs succesfully but the error didn't disappear. It is ignored by eclipse.

Hibernate not connecting with MySql

Stuck at this place I am new to hibernate and making a sample code after watching tutorial However I am stuck connecting hibernate with MySql.
Here is hibernate.cfg.xml placed in the source folder
<?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>. -->
<hibernate-configuration
xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration
hibernate-configuration-4.0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</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.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>
<property name="current_session_context_class">thread</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.javapapers.UserDetails" />
</session-factory>
</hibernate-configuration>
And here is my HibernateTest.java file
package com.javapapers;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user=new UserDetails();
user.setUserId(1);
user.setUserName("Mannu");
System.out.println("Here");
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
System.out.println("Not even printed");
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
Here is UserDetails.java
package com.javapapers;
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;
}
}
And Here is Error Report
Here
Nov 11, 2015 2:23:03 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.2.Final}
Nov 11, 2015 2:23:03 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Nov 11, 2015 2:23:03 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Exception in thread "main" org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 10 and column 56 in RESOURCE hibernate.cfg.xml. Message: cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:133)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
at org.hibernate.cfg.Configuration.configure(Configuration.java:259)
at org.hibernate.cfg.Configuration.configure(Configuration.java:245)
at com.javapapers.HibernateTest.main(HibernateTest.java:15)
Caused by: javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 10; columnNumber: 56; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.]
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.handleStreamException(UnmarshallerImpl.java:420)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:401)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:374)
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:126)
... 6 more
Caused by: org.xml.sax.SAXParseException; lineNumber: 10; columnNumber: 56; cvc-elt.1: Cannot find the declaration of element 'hibernate-configuration'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1906)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.startElement(ValidatorHandlerImpl.java:570)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.startElement(ValidatingUnmarshaller.java:86)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:60)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.handleStartElement(StAXEventConnector.java:246)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXEventConnector.bridge(StAXEventConnector.java:115)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:398)
... 8 more
Create SessionFactory like that. It worked at Hibernate 4.3.
Configuration configuration = new Configuration();
configuration.configure();
private static ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
private static SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
And it's total violation of factory pattern to do that in main. Make separate class for it.

Hibernate: javax.naming.NoInitialContextException (using DAO generated by Hibernate)

I'm new to Hibernate. Using Hibernate 3.0 from Eclipse indigo.
The topic is discussed here and the answer is not helpful, Hibernate: javax.naming.NoInitialContextException (Component Mapping via Annotations)
i.e. I tried removing name from session-factory and still getting the error.
Am I missing something? Can anyone help with this?
The error is as follows:
Feb 6, 2013 3:59:05 PM PatternsHome getSessionFactory
SEVERE: Could not locate SessionFactory in JNDI
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:305)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:342)
at javax.naming.InitialContext.lookup(InitialContext.java:409)
at PatternsHome.getSessionFactory(PatternsHome.java:26)
at PatternsHome.<init>(PatternsHome.java:21)
at OutputProcessing.saveData(OutputProcessing.java:47)
at OutputProcessing.FPFileOutputWriter(OutputProcessing.java:110)
at OrderPatternFileCreate.main(OrderPatternFileCreate.java:84)
Exception in thread "main" java.lang.IllegalStateException: Could not locate SessionFactory in JNDI
at PatternsHome.getSessionFactory(PatternsHome.java:29)
at PatternsHome.<init>(PatternsHome.java:21)
at OutputProcessing.saveData(OutputProcessing.java:47)
at OutputProcessing.FPFileOutputWriter(OutputProcessing.java:110)
at OrderPatternFileCreate.main(OrderPatternFileCreate.java:84)
Hibernate configuration 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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show sql">true</property>
<mapping resource="hibernate_db_mapping.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The DAO file is generated by Hibernate and outline is given as:
public class PatternsHome {
private static final Log log = LogFactory.getLog(PatternsHome.class);
private final SessionFactory sessionFactory = getSessionFactory();
protected SessionFactory getSessionFactory() {
try {
return (SessionFactory) new InitialContext()
.lookup("SessionFactory");
} catch (Exception e) {
log.error("Could not locate SessionFactory in JNDI", e);
throw new IllegalStateException(
"Could not locate SessionFactory in JNDI");
}
}
.....
}
I'm not able to make this work on a stand alone. But I created a generic DAO with HibernateUtil and created sessionFactory using
sessionFactory = new Configuration().configure(new File("hibernate.cfg.xml")).buildSessionFactory();
and accessed DB in my DAO using
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try{
transaction = session.beginTransaction();
session.save(myData);
transaction.commit();
System.out.println("Data is Saved");
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
This worked.

Categories

Resources