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();
Related
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
I'm trying to reverse Engeneer my simple MYSQL DB using Hibernate Configuration with eclipse IDE.But getting below error.
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3307/client1_db
I went through similar issues. This is a Marven Web Project and I can see the MYSQL_connector_java_5.1.34.jar is there under Marven Dependencies library. Some had suggested "No suitable driver found" means the drivers are loading but an issue with the DB connection. I have tried to connect to the localhost and the DB was created using MySQL workbench and it is accessible. I even tried using myphp admin and the DB is accessible.
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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/bookshop</property>
<property name="connection.username">root</property>
<property name="connection.password">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>
<!-- 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 the existing tables and create new one -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
Then I tried using different server port 3307 as below. Still the same error.
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3307/client1_db</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>
The full Error Message
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3307/client1_db
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:189)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:173)
at org.hibernate.cfg.reveng.dialect.AbstractMetaDataDialect.getConnection(AbstractMetaDataDialect.java:121)
at org.hibernate.cfg.reveng.dialect.AbstractMetaDataDialect.getMetaData(AbstractMetaDataDialect.java:60)
at org.hibernate.cfg.reveng.dialect.AbstractMetaDataDialect.caseForSearch(AbstractMetaDataDialect.java:163)
at org.hibernate.cfg.reveng.dialect.JDBCMetaDataDialect.getTables(JDBCMetaDataDialect.java:22)
at org.hibernate.cfg.reveng.JDBCReader.processTables(JDBCReader.java:476)
at org.hibernate.cfg.reveng.JDBCReader.readDatabaseSchema(JDBCReader.java:74)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.jboss.tools.hibernate.runtime.common.Util.invokeMethod(Util.java:43)
at org.jboss.tools.hibernate.runtime.common.AbstractJDBCReaderFacade.readDatabaseSchema(AbstractJDBCReaderFacade.java:44)
at org.hibernate.eclipse.console.workbench.LazyDatabaseSchemaWorkbenchAdapter$2.execute(LazyDatabaseSchemaWorkbenchAdapter.java:132)
at org.hibernate.console.execution.DefaultExecutionContext.execute(DefaultExecutionContext.java:63)
at org.hibernate.console.ConsoleConfiguration.execute(ConsoleConfiguration.java:107)
at org.hibernate.eclipse.console.workbench.LazyDatabaseSchemaWorkbenchAdapter.readDatabaseSchema(LazyDatabaseSchemaWorkbenchAdapter.java:124)
at org.hibernate.eclipse.console.workbench.LazyDatabaseSchemaWorkbenchAdapter.getChildren(LazyDatabaseSchemaWorkbenchAdapter.java:64)
at org.hibernate.eclipse.console.workbench.BasicWorkbenchAdapter.fetchDeferredChildren(BasicWorkbenchAdapter.java:104)
at org.eclipse.ui.progress.DeferredTreeContentManager$1.run(DeferredTreeContentManager.java:219)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:63)
Hibernate Configuration screenshot
Package Explore
Please visit the below page :
https://javarevisited.blogspot.com/2016/09/javasqlsqlexception-no-suitable-driver-mysql-jdbc-localhost.html
Instead of doing the reverse engineering directly I first added the Database to the Eclipse providing JDBC driver path. After testing the connection was successful then performed the reverse engineering and it was successful.
Steps >
01. Go to Data Source Explore
Add the DB connection
Make sure you map the JDBC drivers
04.Test at the end. Make sure your server is running..
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>
I am new bee to Hibernate and trying out things.
One thing that seems to amuse all is how to connect to different databases?
I have two questions here:
If in the same web app I need to connect to MySQL and Oracle, how do I do it?
I am using MySQL and have two databases test1 and test2, how to connect and retrieve data?
I have read in a blog that we can create different configuration files and do it.
I tried it but was not sucessful.
Here's what I tried:
SessionFactory sf = (SessionFactory) new Configuration().configure(path);
Where path is the path of the config file.
Is this the right way?
Using annotation mappings as an example:
Configuration cfg1 = new AnnotationConfiguration();
cfg1.configure("/hibernate-oracle.cfg.xml");
cfg1.addAnnotatedClass(SomeClass.class); // mapped classes
cfg1.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf1 = cfg1.buildSessionFactory();
Configuration cfg2 = new AnnotationConfiguration();
cfg2.configure("/hibernate-mysql.cfg.xml");
cfg2.addAnnotatedClass(SomeClass.class); // could be the same or different than above
cfg2.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf2 = cfg2.buildSessionFactory();
Then use sf1 and sf2 to get the sessions for each database. For mapping files, you just use cfg.addClass instead of addAnnotatedClass. Put the cfg.xml files in the root package in this case. Those will have the Oracle or MySQL dialect and connection information.
It cannot be done using one hibernate configuration file. You need to have two configurations files for it.
To configure mysql database
hibernate-mysql.cfg.xml
To configure oracle database
hibernate-oracle.cfg.xml
In Details, mysql configuration file be like this.
<?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">PASSWORD</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/UR_DB_NAME</property>
<property name="hibernate.connection.username">USERNAME</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="domain.EmployeeMysql"></mapping>
</session-factory>
</hibernate-configuration>
In Details, oracle configuration file be like this.
<?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">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">PASSWORD</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:UR DB NAME</property>
<property name="hibernate.connection.username">USERNAME</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<mapping class="domain.EmployeeOracleSql"></mapping>
</session-factory>
</hibernate-configuration>
And code should be like this.
mysql configuration
private static SessionFactory sessionAnnotationFactory;
sessionAnnotationFactory = new Configuration().configure("hibernate-mysql.cfg.xml").buildSessionFactory();
Session session = sessionAnnotationFactory.openSession();
oracle sql configuration
sessionAnnotationFactory = new Configuration().configure("hibernate-oracle.cfg.xml").buildSessionFactory();
Session session = sessionAnnotationFactory.openSession()
Ideally you should move to Distributed transaction type of system[using Java Transaction Analyzer org.hibernate.transaction.JTATransactionFactory] in this case. If you are running in JBoss App Server, you can do it by using "Distributed Transaction Managers". You can learn more about it here.
You can also use a catalog with the value of the other database
#Table(name = "foo", schema = "bar", catalog = "OtherDatabase")
You can also Add mapping class in configuration.xml file
Note : this is for annotations and for resources use resources keyword instead of class
<mapping class="packageName.classNmae1"/>
<mapping class="packageName.classNmae2"/>
You can connect two databases test1 and test2, retrieve data with only one hibernate with some tricks:
hibernate SQLQuery: just add database name with the table "select * from test1.table1", "select * from test2.table2"
hibernate persistence: using the key schema in the hibernate mapping xml
<class name="Table1Class" table="table1" schema="test1">
<class name="Table2Class" table="table2" schema="test2">
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