JPA persist generic entity - apache

I need some helps with JPA 2.1 (and ORM Hibernate).
I have some entity (3-4) mapped in database table, and I can see their rows into separate primefaces datatable. I also export these data in .xls file with apache poi.
Everything works perfectly.
Now, I need to import and read an excel file (I already done it), and insert the new information in a table.
Can I implement a generic JPA method to insert (make persistent) a series of data?
Something like this
EntityManager em = getEntityManager;
em.getTransaction().begin();
Employee employee = new Employee();
employee.setFirstName("Bob");
....
em.persist(employee);
em.getTransaction().commit();
But with "generic" and not specific entity (in this case is "Employee"), so as to create an unique persistent method for all entities, and not several specific method for each entity? (Whereas they also have different names of columns).
Thank you all!

You need a way to determine the following:
What entity type should the excel row be implied as.
What is the property mappings between the various excel columns and the entity properties.
With those pieces of information, you could easily use a no-arg constructor for each of you entity classes to construct a new instance, use a library like BeanUtils or equivalent to set the property values based on your column to property mappings and then persist it.
From a JPA persistence perspective, there is absolutely nothing here that affects that.

Related

How to add custom (user defined) properties to entities with EclipseLink?

I'd like to add user-defined custom fields to an existing entity in EclipseLink. For performance reasons, I want them to be stored directly in the entity's table, and I also want them to be "first class citizens", i.e. usable in queries.
From an implementation standpoint, the entity should have two methods to set and get custom fields:
public Object getCustomProperty(String key) { ... }
public void setCustomProperty(String key, Object value) { ... }
When setting a custom property foo, EclipseLink should store the value in the entity's table in a field named custom_foo.
From an end user standpoint, I would like to provide a GUI where the user can define and manage custom fields, which are then dynamically added to or removed from the database.
Is this possible in EclipseLink?
Regards,
Jochen
Check out EclipseLink's Extensibility feature
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Advanced_JPA_Development/Extensible_Entities
This with support for adding columns:
http://wiki.eclipse.org/EclipseLink/DesignDocs/368365
seems somewhat like what you are asking for - except for the conflicting statement that it shouldn't store in the main table, then later state it should store in the entity's table "custom_foo" column.
You will need to create the GUI that creates the mappings. Eclipselink ships with a metadata source implementation that reads from an orm.xml file, so you may have to write your own implementation for EclipseLink to use if your GUI cannot write to an orm file.

NHibernate: Returning only two properties of an entity in a Dictionary

We are using Oracle 10g database, NHibernate, WCF and Silverlight 3.0 in our project
The situation we have is that the entities in my project have many properties. But for certain situations, like showing the options in dropdown, I only want to retrieve the list of ID and Name field for that entity. I do not want to return a list of the entire entity object as a whole as there are many columns in the table. Presently I am using two SELECT queries: one to fetch the list of IDs and second to fetch the list of Names separately. Then I join these two queries and form a Dictionary and pass it to the UI.
The concern for me is that would it be possible to achieve this in a single query itself?
One approach that I know of is to create a new class having only the ID and Name property, import it into NHiberante and then form a list of this new class and send it to the UI. I want to avoid this approach for now as there are many tables for which I have to implement this functionality and hence I will have to create many new classes and corresponding xml files.
Any sort of help would be greatly appreciated.
Here is one way to do it using the Criteria API, Projections and AliasToBean. If it's a simple non-persistent class containing Id and Name you can reuse the class. NHibernate query CreateCriteria

NHibernate: Dynamic Table Mapping

I have a scenario where I want to persist document info record to a table specific to the typo of document, rather than a generic table for all records.
For example, records for Invoices will be stored in dbo.Doc_1000 and records for Receipts will be stored in dbo.Doc_2000 where 1000 and 2000 are id autogenerate and store in well-known table (dbo.TypeOfDoc.
Furthermore each dbo.Doc.xxx table have a group of system column (always the same) and could have a group of dynamic column (metadata).
Tables dbo.Doc.xxx and eventually dynamic column are clearly created at runtime.
If this is possible with NHibernate???
Thanks.
hope that I got your point. I am currently looking for a solution for a problem that looks similar. I want to integrate a feature in my application where the admin user can design an entity at runtime.
As far as I know, once the SessionFactory is configured and ready to use, there is no way to modify the mapping used by nhibernate. If you want to use a customized table structure that is configured, created and modified at runtime, you should have a place where a corresponding mapping lives, e.g. as a nhibernate mapping xml file and you have to set up a new SessionFactory each time you change the database model to reflect these changes.

How can one delete an entity in nhibernate having only its id and type?

I am wondering how can one delete an entity having just its ID and type (as in mapping) using NHibernate 2.1?
If you are using lazy loading, Load only creates a proxy.
session.Delete(session.Load(type, id));
With NH 2.1 you can use HQL. Not sure how it actually looks like, but something like this: note that this is subject to SQL injection - if possible use parametrized queries instead with SetParameter()
session.Delete(string.Format("from {0} where id = {1}", type, id));
Edit:
For Load, you don't need to know the name of the Id column.
If you need to know it, you can get it by the NH metadata:
sessionFactory.GetClassMetadata(type).IdentifierPropertyName
Another edit.
session.Delete() is instantiating the entity
When using session.Delete(), NH loads the entity anyway. At the beginning I didn't like it. Then I realized the advantages. If the entity is part of a complex structure using inheritance, collections or "any"-references, it is actually more efficient.
For instance, if class A and B both inherit from Base, it doesn't try to delete data in table B when the actual entity is of type A. This wouldn't be possible without loading the actual object. This is particularly important when there are many inherited types which also consist of many additional tables each.
The same situation is given when you have a collection of Bases, which happen to be all instances of A. When loading the collection in memory, NH knows that it doesn't need to remove any B-stuff.
If the entity A has a collection of Bs, which contains Cs (and so on), it doesn't try to delete any Cs when the collection of Bs is empty. This is only possible when reading the collection. This is particularly important when C is complex of its own, aggregating even more tables and so on.
The more complex and dynamic the structure is, the more efficient is it to load actual data instead of "blindly" deleting it.
HQL Deletes have pitfalls
HQL deletes to not load data to memory. But HQL-deletes aren't that smart. They basically translate the entity name to the corresponding table name and remove that from the database. Additionally, it deletes some aggregated collection data.
In simple structures, this may work well and efficient. In complex structures, not everything is deleted, leading to constraint violations or "database memory leaks".
Conclusion
I also tried to optimize deletion with NH. I gave up in most of the cases, because NH is still smarter, it "just works" and is usually fast enough. One of the most complex deletion algorithms I wrote is analyzing NH mapping definitions and building delete statements from that. And - no surprise - it is not possible without reading data from the database before deleting. (I just reduced it to only load primary keys.)

Fluent Nhibernate and Dynamic Table Name

I've got a parent and child object. Depending on a value in the parent object changes the table for the child object. So for example if the parent object had a reference "01" then it will look in the following table "Child01" whereas if the reference was "02" then it would look in the table "Child02". All the child tables are the same as in number of columns/names/etc.
My question is that how can I tell Fluent Nhibernate or nhibernate which table to look at as each parent object is unique and can reference a number of different child tables?
I've looked at the IClassConvention in Fluent but this seems to only be called when the session is created rather than each time an object is created.
I found only two methods to do this.
Close and recreate the nhibernate session every time another dynamic table needs to be looked at. On creating the session use IClassConvention to dynamically calculate the name based on user data. I found this very intensive as its a large database and a costly operation to create the session every time.
Use POCO object for these tables with custom data access.
As statichippo stated I could use a basechild object and have multiple child object. Due to the database size and the number of dynamic table this wasn't really a valid option.
Neither of my two solutions I was particularly happy with but the POCO's seemed the best way for my problem.
NHibernate is intended to be an object relational mappers. It sounds like you're doing more of a scripting style and hoping to map your data instead of working in an OOP manner.
It sounds like you have the makings of an class hierarchy though. What it sounds like you're trying to create in your code (and then map accordingly) is a hierarchy of different kinds of children:
BaseChild
--> SmartChild
--> DumbChild
Each child is either smart or dumb, but since they all have a FirstName, LastName, Age, etc, they all are instances of the BaseChild class which defines these. The only differences might be that the SmartChild has an IQ and the DumbChild has a FavoriteFootballTeam (this is just an example, no offense to anyone of course ;).
NHibernate will let you map this sort of relationship in many ways. There could be 1 table that encompasses all classes or (what it sounds like you want in your case), one table per class.
Did I understand the issue/what you're looking for?