Retrieving table metadata via Hibernate - java

Is there a simple way to retrieve table metadata (e.g. primary key and foreign keys) from a relational database, via Hibernate?
There are numerous XInformation interfaces in the package org.hibernate.tool.schema.extract.spi (e.g., TableInformation, PrimaryKeyInformation, ForeignKeyInformation), as well as an InformationExtractor interface, but no documented ways of how to instantiate them from a database session.
Using plain vanilla JSBC allows the retrieval of the metadata via
DatabaseMetaData metadata = connection.getMetaData();
Apparently the corresponding mechanism in Hibernate 5 is to register an org.hibernate.integrator.spi.Integrator object in the properties used to create SessionFactory objects to connect to the database, as discussed in this questiοn:
How to discover fully qualified table column from Hibernate MetadataSources
Is there any way of getting the above information as in JDBC, i.e. without modifying the session configuration?

Related

Get data through Hibernate without Entity classes

We use Hibernate and annotations to map our db and entities. But for some data tables I don't want entity classes (Because these table names and all are keep changing) so that the application will be more dynamic
So is it possible using hibernate to load data from a table without a entity class?
If so how?
Hibernate provides a way to execute SQL query and to map it to an entity or any class : native sql queries.
Use plain JDBC. I'm not sure what you mean by "table names and all are keep changing" but it sounds like a bad idea to me.
What you could do is create the sql query using string concatenation then use plain JDBC to execute it. That way you can keep table names dynamic.
If Persistence class won't be used, then the data encapsulation won't occur thus data can be accessed directly.
Hibernate Queries interact with the POJO class to fetch data.
Query, Criteria, HQL all the classes use the POJO for fetching data.
Hibernate Framework was mainly designed for the ORM Mapping.
Thus without POJO class, not possible to interact with the database.
Thus using JDBC connection would be the option left.
Use Dynamic models introduced in Hibernate 5 version - 5.4.0.Final
Hibernate Dynamic Models
To achieve this you will need HBM files created.
Session s = openSession();
Transaction tx = s.beginTransaction();
Session s = openSession();
// Create a customer
Map david = new HashMap();
david.put("name", "David");
// Create an organization
Map foobar = new HashMap();
foobar.put("name", "Foobar Inc.");
// Link both
david.put("organization", foobar);
// Save both
s.save("Customer", david);
s.save("Organization", foobar);
tx.commit();
s.close();
Here Customer & Organization are table names
Organization is Parent of Customer.
Click on the above link for more details

How shall I generate an id for each record in a database table?

I am following https://www.javatpoint.com/crud-in-servlet
to create an CRUD application in servlets and mysql.
Each user inputs his information in a webpage and submit to the web server, which then invokes a servlet SaveServlet to save the information as a record in a database table. The database table however has an additional "id".
SaveServlet.java doesn't create an id for each record. So I was wondering how to create an id for each record?
Thanks.
If you are using jpa/hibernate then your entity must be having the #Id annotation on the record id field (you dont need to set it, it will be done automatically based on you Id generation mechanism defined in the entity class and database schema).
if you are using plain jdbc for persisting records then you need to check the database how primary key is defined. for oracle you can your sequence.nextvalue to set the primary key.

Hibernate. How to create an empty table from ResultSetMetaData?

I have a ResultSetMetaDataobject.
PreparedStatement ps=con.prepareStatement("select var1, var2 from test1, test2");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
I need to create an new empty table with all the fields in the above ResultSetMetaData
Open a new connection in different database
Use the meta data above
Create a new empty table with this meta data
I can see two possible solutions
Reflection. In general to create a table with Hibernate, I need to create a bean. But I don't know in advance what fields the ResultSetMetaData will contain . Should I create this bean with reflection?
HQL CREATE TABLE . Is this possible?
What is the simplest way to do this? How can I do this?
Couple of solutions that I can think of:
SchemaExport - Iterate through your ResultSetMetaData which exposes API's like getColumnName and getColumnType to get the information you need. Using this information create a hibernate mapping XML and send it to SchemaExport.create.
// yourClassMapper.xml generated in runtime
Configuration config = new Configuration();
config.addResource("yourClassMapper.xml");
new SchemaExport(config).create(true,true)
Native Query - As Usual Iterate through your metadata to figure out what should the columns be.
Using createSQLQuery or even using createNativeQuery
session.createSQLQuery("create table .....").executeUpdate();
This link provides an explanation on how to create custom fields. You can make use of its DOM Parser for 1st approach or create just tables and use the method mentioned in this blog to create custom fields. (Refer to this class MappingManager and its related custom map configuration)
Lastly, You need 2 different datasource to be configured for this. And inject the second database's source for creating session/sessionfactory in above implementations.
I dont think you need to create bean for it. If you want to create new table with same fields then simple fire this query on database using hibernate or jdbc.
SHOW CREATE TABLE tablename
Now simply change the name of the table in query, can be easily done in Java.
Now you does not need to create any bean for newly created table.
There are two ways for fetching data from table in hibernate. First way is get table data in form of bean object, another way is fire sql query and get data in form of Object (Java Class). you can get data in form of Object and Object Array using hibernate.
When we use join query in hibernate, then there is no specific type of bean is available for handling result of join because it contain column from multiple table so you will get data in form of Object and Object Array.
Just get Data in form of Object or Object Array.
Check This Link of my github... not exactly what you want but still will help :
here
I hope I Helped you.

Java persistence API when switching to mongoDB?

I am using Spring JPA with hibernate as implementation . DB vendor is oracle.
I am doing POC how can migrate existing platform to Mongo DB. Some related questions to that ?
Can I continue to use JPA API when switching to Mongo DB?
If Yes to point 1, Can I continue to use hibernate and just migrate DB oracle to Mongo DB or is there any better JPA implementation for Mongo DB ?
At present hibernate takes care saving objects in their respected tables/relation with proper connection. For example :- user object has 1 to many
mapping to address object as user can have multiple address. Now once i save user entity, hibernate first save user object in user table. Get userId
and save it address entity. Now persist address entity in address table
Similarly in mongoDB , I believe there must be API's which must be doing this stuff(under collection instead of table) out of shelf where I don't have to do manually like in JDBC era?
I know mongoDB does not support ACID properties. But then how will I handle atomicity here ?Say user document is saved but some error occurred while saving address object. How as application developer I can revert the entry under user table also ?

Hibernate:how to make entity class with all database fields automatically

I am working on a project with MySQL,Hibernate,Java,GWT
I am making an entity class where i am making each and every field as per the fields in mysql
like there is a table UserInfo with fields ,id,name,password,and many other fields in MySQL
now when i am making an entity class in java/hibernate
I have to create each field i.e id,name,password and others with my hand
I was just wondering if there's a way with which my entity class automatically detects all fields which are in my Database table and make all the fields in java itself and link them with the database fields.
thanks
hibernate has a property called "hibernate.hbm2ddl.auto".
hibernate.hbm2ddl.auto
Automatically validates or exports schema DDL
to the database when the SessionFactory is created. With create-drop,
the database schema will be dropped when the SessionFactory is closed
explicitly.
e.g. validate | update | create | create-drop
you can set the proper value when you start creating your sessionfactory. then you will see the tables were created in your datastore, of course, the table creation was based on your entity classes.
if you want to generate java classes (entities) from your database table. you may want to check hibernate reverse engineering out:
http://docs.jboss.org/tools/3.3.0.M5/en/hibernatetools/html/reverseengineering.html
Try Hibernate Tools.

Categories