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.
Related
I use the Hibernate Reverse Engineering through JBoss Tools > Hibernate Tools to generate Model Classes.
There, when I add the Hibernate Configuration and Run it / Rebuild It, it list all the DBs although I mention only one DB in the hibernate.cfg.xml's hibernate.connection.url.
eg : jdbc:mysql://localhost:3306/booksdb.
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/booksdb</property>
<property name="hibernate.connection.username">xxxx</property>
<property name="hibernate.connection.password">xxxx</property>
</session-factory>
</hibernate-configuration>
Then when I generate the entities code it scans all other Database tables also to generate the entity codes for all. Sometimes it impact by some duplicated tables in different DBs.
Question :
How to do this for single database mentioned in the hibernate.connection.url?
Hibernate Code Generation Configurations > Main
Hibernate Code Generation Configurations > Exporters
Hibernate version : 5.4
MySQL version Info
innodb_version:5.7.26
protocol_version:10
version:5.7.26-0ubuntu0.18.04.1
version_comment:(Ubuntu)
version_compile_machine:x86_64
version_compile_os:Linux
In this screen go to setup near reveng.xml. It will ask you to create a xml, from there you'll be able to exclude the databases you don't want.
<hibernate-reverse-engineering>
<table-filter match-name=".*" exclude="true" match-catalog="YOUR_DATABASE_NAME" />
</hibernate-reverse-engineering>
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.
I am new to Hibernate, As per my knowledge, when hbm2ddl.auto is set to 'update', it should create a table if its doesn't exist, it should create a new column automatically if the new 'property' tag for column is added in mapping file. Right?
But whenever i am trying to run my class, it is throwing "Table or view doesn't exist" instead of creating it. I am using hibernate v5.10
Here's my POC example i am trying to run. Thanks in advance.
Mapping file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.nt.domain.Customer" table="CUSTOMER">
<id name="custNo" length="10" type="int" column="CUSTNO"/>
<property name="customerName" length="20" type="string" column="CUSTNAME"/>
<property name="billAmt" length="10" type="int" column="BILLAMT"/>
</class>
</hibernate-mapping>
Configuration
<?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">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:sys</property>
<property name="connection.username">Asif123</property>
<property name="connection.password">Asif123</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="com/nt/domain/customer.hbm.xml"/>
</session-factory>
Main
package com.nt.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.nt.domain.Customer;
public class UpdateTest {
public static void main(String[] args) {
Configuration cfg = new Configuration().configure();
SessionFactory factory = cfg.buildSessionFactory();
Session ses= factory.openSession();
Transaction tx= ses.beginTransaction();
Customer customer = new Customer();
customer.setCustNo(101);
customer.setCustomerName("Asif");
customer.setBillAmt(1245);
ses.save(customer);
tx.commit();
ses.close();
factory.close();
}
}
Customer
package com.nt.domain;
public class Customer {
int custNo;
String customerName;
int billAmt;
//All getters and setters
}
Exception
Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1059)
....
For anyone still searching for an answer, If you want to experience all the functionalities of "update" property like auto table creation, auto adding of columns (both case : if already not available), then go for the 5.0.1.Final version, it is the most stable version supporting them.
I think you need "create", "update" will only update existing tables, see docs:
https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/ch03.html
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
I'm trying to run HQL queries in IntelliJ's Hibernate Console. I've added the datasource to the Data Sources view and added my hibernate.cfg.xml to the Hibernate facet such that in appears in the Persistence view. The content of hibernate.cfg.xml is:
<?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="connection.url">jdbc:mysql://localhost/mmanager</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
<property name="dialect">com.puca.core.util.db.MySQLInnoDBDialect</property>
<!-- mapping files -->
<mapping resource="com/puca/messagemanager/api/model/XmlApiDlrMapping.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The .hbm.xml is shown in green, whereas if I change it to a file that doesn't exist it is shown in red, so it seems that IntelliJ can find it. However, if I run a simple query in the console like:
from XmlApiDlrMapping xmlApiDlrMapping
where xmlApiDlrMapping.retries = 5
I get an error:
java.lang.RuntimeException: org.hibernate.MappingNotFoundException: resource: com/puca/messagemanager/api/model/XmlApiDlrMapping.hbm.xml not found
at org.hibernate.cfg.Configuration.addResource(Configuration.java:563)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1587)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1555)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1534)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1508)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1462)
I'm using IntelliJ 10.5.4.
It's exactly what it says in the error message. The mapping XML file is missing:
com/puca/messagemanager/api/model/XmlApiDlrMapping.hbm.xml
These files are used to map table columns to your entity class fields.
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/tutorial.html#tutorial-firstapp-mapping