Error switching from Hibernate Annotations to hbm.xml file - java

So while working on my project I originally used Hibernate Annotations #Entity, #Table, #Column, #SequenceGenerator, and #GeneratedValue in my java class and was able to successfully add items to my Oracle database.
Now I'm trying to replicate the same thing, but using a *.hbm.xml file and encountering problems.
Here is the original Java Class code with the annotations commented out:
//#Entity
//#Table (name="client")
#SequenceGenerator(name="seq_client",sequenceName="BIMB2013WMMEE.seq_client",
allocationSize=1, initialValue=1)
public class Client {
//Fields
//#Id
//#GeneratedValue(strategy=GenerationType.SEQUENCE)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_client")
//#Column(name="CLIENT_ID")
private int id;
//#Column(name="CLIENT_NAME")
private String clientName;
//#Column(name="CLIENT_CODE")
private String clientCode;
Here is the corresponding hbm.xml file which is located in the src directory of my project.
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#endeavour.us.manh.com:1523/pso11r2f</property>
<property name="connection.username">BIMB2013WMMEE</property>
<property name="connection.password">BIMB2013WMMEE</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Finally here is the Eclipse Error code:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.luv2code.hibernate.demo.entity.Client
I didn't make any changes to the class that is actually creating the object and adding it to the database via a session... do I need to?
Thanks for the help!!

The xml file which you have shown is hibernate configuration file it is not hbm.xml file.
You have to make "classname.hbm.xml" file for each persistent entity you make - in your case it is your Client class. so you have to make a Client.hbm.xml file. After that you have to add that resource to your configuration file and Hibernate Utility file. You might find this helpful.
http://www.mkyong.com/hibernate/how-to-add-hibernate-xml-mapping-file-hbm-xml-programmatically/

I think you may have forgotten mapping tags to list all the resources that are using hibernate persistence in your project.
Here's an example :
hibernate.cfg.xml
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:file:db/personh2db;DB_CLOSE_DELAY=-1;MVCC=TRUE</property>
<property name="connection.username">sa</property>
<property name="connection.password"/>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.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">create</property>
<mapping resource="com/example/model/Person.hbm.xml"/>
<mapping resource="com/example/model/Properties.hbm.xml"/>
</session-factory>

Related

Caused by: org.postgresql.util.PSQLException: database doesn't exist when trying to auto-create database

I have this hibernate.cfg.xml:
<!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">org.postgresql.Driver</property>
<property name="connection.url">
jdbc:postgresql://localhost/DatabaseName?createDatabaseIfNotExist=true
&useUnicode=yes&characterEncoding=UTF-8
</property>
<property name="connection.username">postgres</property>
<property name="connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">5</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQL9Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</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.main.User"/>
</session-factory>
</hibernate-configuration>
which is supposed to create both tables (for the User entity and the database DatabaseName). However, it doesn't create a database and fails with an error on this line:
sessionFactory = configuration.buildSessionFactory();
What can I do to make it autocreate database titled DatabaseName?
To create database you have to create is manually you can use IDEs for that or cmd to create your DB
And To create Tables you can use create in place of update
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
It will create a schema and then you will use an update for the next startup if you don`t want to recreate your tables

Hibernate 5.2 encrypt configuration properties

In my application build on Hibernate 5.2.11 there are many hibernate configuration file with username, password and connection url.
I would like to encrypt that data.
My configuration file is like this:
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:localhos</property>
<property name="connection.username">username</property>
<property name="connection.password">passowrd123</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">2</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
</session-factory>
</hibernate-configuration>
Any suggestion?
Use a property placeholder then add your database config to a properties file on the server:
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>file:${configDir}/database.properties</value>
</property>
</bean>
Then
<property name="connection.url">${url}</property>
<property name="connection.username">${username}</property>
<property name="connection.password">${passowrd}</property>
Then your database.properties which is securely on the server will be
url=jdbc:oracle:localhost
usuername=username
password=passowrd123
Then when you start your java app add a system parameter to define the configDir location, for example:
.... -DconfigDir=/opt/config
See examples here
Generally - encrypting/hiding anything what resides on the client's side (workstation/mobile/..) you can consider more like obfuscation or encoding.
In theory - you may set the Hibernate properties programatically (see Setting properties programmatically in Hibernate) reading your data from an encrypted file.
The problem is - where do you put your encryption keys? The keys has to be available to the application anyway somewhere.

Java Hibernate Schema Update does nothing

I am working with Hibernate on Java with a MySQL database. If I set hbm2ddl.auto to create`, all current tables are dropped and recreated correctly, but if I set it to "update" it does nothing to the database despite reporting the following line to the console:
INFO: HHH000228: Running hbm2ddl schema update
For reference, the code I am using to set up the database is:
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure()
.build();
While my cfg.xml file looks like:
<?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://127.0.0.1:3306/testdatabase</property>
<property name="connection.username">xxxxxxxx</property>
<property name="connection.password">xxxxxxxx</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>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.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>
<!-- Names the annotated entity class -->
<mapping class="com.test.case.Example"/>
</session-factory>
</hibernate-configuration>
Obviously since the create is working, I see no need to show my annotated class.
Edit:
The changes I expect to happen are basically to correct the database column types to the correct ones. Before running the update I change the column types in MySql to something different from the annotated schema but on update it's not correcting it as would be expected. In contrast when I dropped the table altogether the update did work, it would seem update is not as fully featured as expected?
Service registry requires some properties from the configuration. And because you are using non-standard name/location of the hibernate configuration file
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure("cfg.xml")
.build();

Hibernate auto create database

I have a Java EE Hibernate project, and I'm using MySQL as a database.
I want that when I first time run the project, it will create the database automatically.
This is my hibernate.cnf.xml:
<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/InternetProject</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping class="entities.Business" />
<mapping class="entities.Coupon" />
<mapping class="entities.User" />
<mapping class="entities.LastLogin" />
</session-factory>
</hibernate-configuration>
When I first time run this project on another computer, how can I make the database InternetProject to be created?
According to the config file, it might already do it and I'm not aware to it.
Thanks in advance.
<property name="hibernate.hbm2ddl.auto">create</property>
will create tables. But it will not create database. Change the connection url to generate the database.
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/InternetProject?createDatabaseIfNotExist=true</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
Update : character encoding when creating database
<property name="connection.url">
jdbc:mysql://localhost/InternetProject?createDatabaseIfNotExist=true&useUnicode=yes&characterEncoding=UTF-8
</property>
<property name="hibernate.hbm2ddl.auto">create</property>
will do
Hibernate will not create the database for you, only the tables. To create the database you need to tell MySQL to create it if it does'nt already exist by adding a parameter to the URL. E.g.:
jdbc:mysql://db:3306/mydatabase?createDatabaseIfNotExist=true
There are multiple option for auto property.
create - It creates new tables corresponding mapping or annotation. It drops existing tables and data.
update - It keeps existing data and tables. It updates schema. here we have to take care contrants.
create-drop - It is same like create but once session gets closed it drops everything.
validate - it validates or matches schema with map or annotation. It's valid for Production environment.
<!-- create create-drop validate update -->
<property name="hbm2ddl.auto">update</property>
I hope it helps.

Hibernate Mapping Files Not Found(MappingNotFoundException)

I followed this tutorial: http://manikandanmv.wordpress.com/2011/04/13/hibernate-basics-simple-example/
This is my file structure
http://i.stack.imgur.com/sX3nn.jpg
When I run Java Applet, I get this error
Initial SessionFactory creation failed.org.hibernate.MappingNotFoundException: resource: src/com/bookstore/bookapp.hbm.xml not found
However, I have that file there as you can see it. When I put the file under
workspace-windows\226project1\src\com\bookstore
I'm still facing this error even then, Can someone help?
This is my hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.url">jdbc:postgresql://localhost:5432/postgres</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.username">postgres</property>
<property name="connection.password">rocker123</property>
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="src/com/bookstore/bookapp.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Move your mapping files into src/main/resources. Only .java files belong in src/main/java.
There is an example project on github showing how to correctly reference XML mapping files from a hibernate.cfg.xml. Please refer to https://github.com/zzantozz/testbed/tree/master/hibernate-with-xml-mappings

Categories