hibernate.hbm2ddl.auto - Create-Drop is not working in Hibernate - java

I am using create-drop for hibernate and its not working. I am restarting my project but still its not dropping my old table and its data.
<property name="hibernate.hbm2ddl.auto">create-drop</property>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/HibernateConfiguration 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/demo</property>
<property name="connection.username">root</property>
<property name="connection.password">****</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="hibernate.current_session_context_class">thread</property>
<!-- Names the annotated entity class -->
<mapping class="domains.Test"/>
<mapping class="domains.LoginDetails"/>
<mapping class="domains.User"/>
</session-factory>
</hibernate-configuration>
I found that, I don't know if I am wrong or correct. While I was running my application hibernate was not dropping any table nor creating any table even though create-drop is mentioned in configuration file. But when I created one new object and save method is called hibernate dropped all tables and created all tables again. So question raised in my mind that may be hibernate is only performing operation when there is a sessionFactory object is there. I am using Singleton pattern to create sessionFacotry object. So until I am not doing any CRUD operation sessionFactory object will not be created and hence it was not dropping or recreating all tables. Please correct me if I am wrong.
public static SessionFactory sessionFactory;
private HibernateUtility(){}
public static SessionFactory getSessionFactory() {
try{
if (sessionFactory == null) {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
}catch(Exception e) {
System.out.println(e);
}
return sessionFactory;
}
Until I am calling this method from DAO hibernate not doing any create or drop table operation. This is what I am trying to say. Until sessionFactory object is not created create-drop not working

Analysis
(Note: This is just a guess.)
It seems an instance of the SessionFactory interface is not getting closed (by Tomcat?).
Solution
It is necessary to configure Tomcat to manage the Hibernate's SessionFactory appropriately. Please refer to:
Using Hibernate with Tomcat |JBoss Developer.
TomcatHibernate - Tomcat Wiki.
Setup Hibernate Session Factory in Tomcat - Stack Overflow.
dev - Tomcat, JPA, Hibernate and MySQL. The related gist: Integrate Hibernate 4.1 in a raw Tomcat 7 (no JPA, no Spring, etc) ยท GitHub.
configure hibernate with embedded tomcat 7 programmatically - Stack Overflow.

Related

Grails 4 not picking up mapping section of hibernate.cfg.xml file

We are migrating a Grails 2 application to Grails 4.
The application internally consists of a backend in spring/java and a grails front-end. As a result almost all database classes are defined as java classes with the correct hibernate annotations. To support gorm we added the required <mapping .../> entries for the packages and the classes to hibernate.cfg.xml, which is working correctly in grails 2.
To migrate hibernate.cfg.xml we did set the location property in application.yml:
---
hibernate:
cache:
queries: false
use_second_level_cache: false
use_query_cache: false
configLocations: classpath:hibernate.cfg.xml
and we moved the actual hibernate.cfg.xml file to the /src/main/resources folder.
However, the application does not seem to be able to read anything from the database. There is no error, but also no data.
When debugging, I noticed that entityPersisterMap in the MetamodelImpl class only had 8 persisters, and they were all for classes defined in the grails/domain folder (we have 8 classes there). But we would expect several hundreds of entries in this map, as there are that amount of tables.
the xml file looks like:
<hibernate-configuration>
<session-factory>
<property name="hibernate.session_factory_name">Hibernate_Session_Factory</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="net.sf.ehcache.configurationResourceName">ehcache-hibernate.xml</property>
<!-- connection settings -->
<property name="hibernate.connection.release_mode">after_transaction</property>
<!-- This should be equal to Constants.HIBERNATE_BATCH_SIZE -->
<property name="hibernate.jdbc.batch_size">100</property>
<!-- Debugger helpers -->
<property name="hibernate.show_sql">false</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<!-- https://hibernate.atlassian.net/browse/HHH-9106 -->
<property name="hibernate.event.merge.entity_copy_observer">allow</property>
<!-- Mappings, only needed to help GROM, otherwise all the mappings are done with annotations -->
<mapping package="com.server.metafields.db"/>
<mapping class="com.server.metafields.db.MetaField"/>
<mapping class="com.server.metafields.db.MetaFieldValue"/>
<mapping class="com.server.metafields.db.MetaFieldGroup"/>
...
</session-factory>
</hibernate-config>
We are using grails 4.0.6
Anybody seeing anything we are doing wrong ?

Anybody can check for me what wrong when I try to connect PostgreSQL by using Hibernate

First, let me list the things I have used:
Eclipse JEE version 2021-03
Apache Tomcat Server 9
Hibernate ORM version 5.2.18.Final
PostgreSQL 14
Java 8
Some driver I have used: the required in lib of Hibernate ORM, postgresql-42.2.22.jar, jaxb-api-1.0.jar
Second is my code:
In the main class, I use it to run the application I let the name of class is CreateStudentDemo in the phucldh.Demo package in the src folder
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// create a student object
Student tempStudent = new Student("Le", "Phuc", "phucldh.work#gmail.com");
// start a transaction
session.beginTransaction();
// save the student object
session.save(tempStudent);
// commit transaction
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Create student demo error: " + e.getMessage());
} finally {
factory.close();
}
}
And to connect to PostgreSQL I have a configuration file hibernate.cfg.xml in the src folder and the content of this file:
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/HibernateLearn</property>
<property name="connection.username">postgres</property>
<property name="connection.password">********</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Set the current session context -->
<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 the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
That all I have done but when I running I have a problem:
INFO: HHH000206: hibernate.properties not found
Exception in thread "main" java.lang.NoSuchMethodError: 'javax.xml.bind.JAXBContext javax.xml.bind.JAXBContext.newInstance(java.lang.Class[])'
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:122)
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:258)
at phucldh.Demo.CreateStudentDemo.main(CreateStudentDemo.java:15)
And I see that line 15 of CreateStudentDemo.java is the line about
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
So I hope that anybody can help me find what I have wrong. Thank everybody very much. Hope all have a nice day.

SQLite dialect into Hibernate-Maven project

i am a java student and i have to do a small project. I have to use Maven and Hibernate ( no Spring frameworks). I use IntelliJ as IDE. The thing is that my teacher recomended me to use SQLite as RDBMS because its very simple, 1 file and there is no need to implement a server inside my app. ( i have no idea to do the last point).
The problem is that when i try to do the "hibernate.cfg.xml " i have no way to configure it because of the lack of information. Seems there is no dialect supported from Hibernate and the info i could find on internet is outdated. Any idea on how i can configure it? Do i really need to use another RDBMS ?
there is a picture of my project structure
this is my hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="connection.url">jdbc:sqlite://db/appiculturedb.sqlite3</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<property name="dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.show_sql">true</property>
<!-- maping with xml-->
<mapping resource="Bodega.hbm.xml" />
<!-- maping with anotations-->
<!-- <mapping class="com.stephane.Bodega" /> -->
</session-factory>
</hibernate-configuration>
After searching for few days, i found that you can use SQLite with Hibernate 5 if you create your own dialect. You also can try to use someone else dialect wich may be risky or outdated. Check this link for more info.
For the moment, hibernate do not support oficially SQLite. Maybe in the future that will change.
If you are searching for an embedded database, you can use H2 wich is supported by Hibernate and seems to be recommended by them.
You also have HSQLDB or Apache Derby.

Running H2 embedded database in spring / hibernate

I am trying to create an spring boot application utilizing hibernate and h2. From what I have found online this can be done but I am having a problem starting the application. Hibernate is complaining that it cannot make a connection to the h2 database I have created.
Caused by: org.hibernate.HibernateException: Unable to make JDBC Connection [jdbc:h2:~/todo]
My theory is that the application needs to start for the database be available but hibernate is not letting the application start without the connection.
Am I on the right track with this theory, has there been similar issues that someone knows how to get around this?
Hibernate config
**<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<!--Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:h2:~/todo</property>
<property name="connection.username">username</property>
<property name="connection.password" />
<!--Set the database dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</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>
<!--Name the annotated Entity classes -->
<mapping class="com.todo.beans.User" />
</session-factory>
</hibernate-configuration>**
h2 config
import org.h2.server.web.WebServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class WebConfiguration {
#Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
}
change following properties in hibernate config
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:mem:todo;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
</property>
Problem is with driver class; you may keep url as it is.
This sample project can help you.
https://github.com/dornala/HotelStackoverflow

Getting hibernate entity error

I am using hibernate in spring app. but due to some problem i can't use spring injection so i manually have to declare the session factory like below
SessionFactory sessionFactory = new AnnotationConfiguration()
.configure("com/vaannila/service/hibernate.cfg.xml")
.buildSessionFactory();
Session session = sessionFactory.openSession();
Registration person = (Registration) session.get(Registration.class, 1);
As i am using annotation in entity class i get the following error
org.hibernate.MappingException: Unknown entity: com.vaannila.domain.Registration
<?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>
<!-- We're using MySQL database so the dialect needs to MySQL as well-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- Enable this to see the SQL statements in the logs-->
<property name="show_sql">true</property>
<!-- This will drop our existing database and re-create a new one.
Existing data will be deleted! -->
<property name="hbm2ddl.auto">update</property>
<mapping class="com.vaannila.domain.Country" />
</session-factory>
</hibernate-configuration>
This could be because of the wrong FQCN entry for the class Registration or, you might be having
import javax.persistence.Entity;
instead of,
import org.hibernate.annotations.Entity;
Make sure your Registration class is annotated correctly with "javax.persistence.Entity".
I am just making sure, I have had same trouble when I missed that.
import javax.persistence.Entity;
#Entity
public class Registration{
}
Another reason could be that you class is not listed in hibernate.cfg.xml:
<mapping class="your.package.Registration"/>
Personally I haven't found the way to force standalone Hibernate scanning entity annotations, so I have pretty big list of mappings inside.

Categories

Resources