Get data through Hibernate without Entity classes - java

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

Related

Update request to DB even if nothing has changed in Entity

I use spring data and hibernate. I have an Entity (TestEntity). I made a custom hibernate type that deserializes one String field to two columns.
If I persist an entity and then change it everything works fine and hibernate sends update query (it makes my type work and update query to DB "splits" my old column to two new).
But my goal is to make this king of migration for every record. I can't use an ordinary DB migration because there is some logic in my custom type.
I want to make something like this:
// here I persist all my entities
List<TestEntity> entities = entityRepository.findAll();
for (TestEntity entity : entities) {
// This piece of code does nothing, because when hibernate merges two entities, it understands, that nothing changed, so it won't send update query.
entityRepository.save(entity);
}
But I want him to send update query, although nothing has changed. Moreover, I want this hibernate behaviour to be in one place only (for example, I will create controller to execute this DB update). What is a solution to my problem? Is there any approach to its solving?
I don't understand why you need it but you need to detach the entity from the session for this to work.
As far as I understand, you need the EntityManger:
#PersistenceContext
private EntityManager entityManager;
...
List<TestEntity> entities = entityRepository.findAll();
for (TestEntity entity : entities) {
entityManager.detach(entity);
entityRepository.save(entity); // or entityManager.unwrap(Session.class).saveOrUpdate();
}
See Spring JpaRepository - Detach and Attach entity

Mapping multiple hibernate Entities inside non-entity java bean

Hi I am using a spring boot app with Hibernate using Oracle as DB.
I have 5 classes named
1.Reqest -> Mapped with Request Table
2.Team -> Mapped with Team Table
3.Partner -Mapped with Partner Table
4.Customer -> Mapped with Customer Table
Now I want to Display a Summary of Request on summary screen of the app where all the information from above-mentioned tables is needed.
Suppose I create a bean class as follows.
public class SummaryBean{
Request req;
Team team;
Customer cust;
Partner part;
//Getter setters;
}
Now since I have all the tables mapped with Java classes I can use hql join query to fetch data.
I don't want use plain SQL query with join and then iterate the resulting Object[] list from hibernate query and stub data into SummaryBean manually.
All the above-mentioned tables have REQ_ID as joining column
My question is How can I make hibernate map the result of that query to SummaryBean object?
Is it possible at all?
You can use constructor query.
Something like
"select new SummaryBean(req, team, cust, part) from (here you join your tables)"
You need to provide a constructor for the SummaryBean with those 4 types.
Note that the SummaryBean class doesn't have to be mapped, but you might have to use fully qualified name in the query (packageName.className).

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.

Will joins work in hibernate if the tables participating in the join are not mapped as entities in hibernate configuration?

Let's suppose, am having two tables in my database and i have to write a join query using two tables. I mapped one of those tables as entity class in my MVC project, but there is no mapping for the other table as entity.
so when i run hql, will that join work?
if it doesn't, and if its necessary to have a mapping, should i specify the constraints (primary/foreign key) between those entities?
My application just reads the data from tables, hence i don't want to waste much time writing entity classes. Is there any easy approach using hibernate?
About your question: HQL only works with mapped entity, but can return not-mapped object with ResultTranformer, but is not your case. You can create minimal definition of unwanted entity with just relationships and property needed by your hql.
Another way to resolve is create the plain SQL query and return only mapped entity with session.createSQLQuery(yourQuerySQL).addEntity(YourMappedEntity.class).
Hibernate only knows what is there in session factory. If you have not defined some entity Hibernate would never know about is, so there is no question about writting hql involving that entity.
Alternatively you can get a connection from the session and then execute custom sql rather than hql.
To use plain sql you can use something like:
getSession().doWork(new Work() {
#Override
public void execute(Connection connection) throws SQLException {
// TODO Auto-generated method stub
}
})

How Can I Query a DB for ResultSet which is not Mapped into an Entity(JPA, JBoss)

I'm running an application in JBoss and Using JPA.
For a report I need a group by query which I expect to return a result set with the following structure example:
count,idA,idB
I did not find a way to implement this in JPA.
What are my best options for implementing this considering I'm developing in JBoss 5, EJB3
You can use a custom holder class and use the NEW keyword in your query:
SELECT NEW com.mycompany.myapp.MyClass(count, idA, idB)
FROM ...
WHERE ...
Of course, MyClass needs to have the proper constructor defined.
In the case of Native queries, you can create a dummy entity into which the result set can be mapped to (Native query will not be mapped into an Object unless its a real managed entity).
The entity is a dummy as it will not be persisted and it only used for mapping the result set of the native query into this entity.

Categories