I imagine this pertains to Hibernate only (I'm just now beginning to use these two frameworks). I have an application that tracks sessions for users. While a session is active, the Session entity is stored in a table for active sessions. When the user goes offline and the session ends, the session is moved to a secondary historical table.
How do I achieve this with Hibernate? Right now I have a Session.hbm.xml file that maps a Session object to the active sessions table. Can I map it to a secondary table and somehow specify to which table I want it to persist when I call saveOrUpdate?
My reputation currently won't allow me to answer my own question this quickly. I don't want anyone to waste their time on this though, since I found an answer, so I'm posting it here as an edit.
I can do this by making use of the entity-name attribute in a mapping file. I created a second mapping, identical to Session.hbm.xml, called HistoricalSession.hbm.xml. In this new mapping file I reference the same Session class, but add:
entity-name="HistoricalSession"
Then I map the object to my second (historical) table just like normal. Calling save() or saveOrUpdate() defaults to using the classname as the entity-name, and saves in my primary table as before. Now, when I want to save a session to the historical table I use the Hibernate API overrides that allow you to specify an entity-name:
saveOrUpdate("HistoricalSession",session);
This accomplishes exactly what I want without need to create another Java class for historical sessions
I can do this by making use of the entity-name attribute in a mapping file. I created a second mapping, identical to Session.hbm.xml, called HistoricalSession.hbm.xml. In this new mapping file I reference the same Session class, but add:
entity-name="HistoricalSession"
Then I map the object to my second (historical) table just like normal. Calling save() or saveOrUpdate() defaults to using the classname as the entity-name, and saves in my primary table as before. Now, when I want to save a session to the historical table I use the Hibernate API overrides that allow you to specify an entity-name:
saveOrUpdate("HistoricalSession",session);
This accomplishes exactly what I want without need to create another Java class for historical sessions
A couple of way to do this could be:
Use a database trigger when the session gets expired the trrigger will move the row to the historical table.
You can create a HistoricalSession extends Session and then do a second mapping for HistoricalSession and write the code to delete from Session and insert into historical session.
Your need sounds like more of an audit like.
Check project Hibernate Envers it might help solve your case in a better way.
Related
I would like to save in my database information about history, for example user "dog" edited field "grass" in table "garden".
I have trigger which saves everything correctly but I have problem with username "dog". Username is logged user's name and I don't now how to "catch" it, because I don't know how to tell my database (PostgreSQL) that this specific user did that.
How can I tell my trigger that it should use value "dog"?
I would like to write an application in Java using Spring Framework and Hibernate Framework. I haven't any app code, because now I'm creating database and thinking about my future application.
Any ideas?
For certain database platforms, they offer context parameters. To use these, you would:
Set the database context parameters.
You can simply use the native SQL interface exposed by Session or EntityManager to accomplish this step.
Register an AfterTransactionCompletionProcess with the Session.
This should basically use the provided Session and clear the database context parameters which you set as part of (1). You would want to do this regardless of whether the transaction was successful or not. This step makes sure those context parameters are cleared prior to giving the JDBC connection back to your connection pool.
Execute your normal ORM changes.
But there is probably a much simplier approach all together, called Hibernate Envers.
Hibernate Envers is designed to mirror your mapped #Entity classes and keep a running history of changes made to your entities. You can easily configure the fields you'd like audited should there only be a subset of fields you're interested in the history on. Additionally, the Envers API exposes an easy way for you to query the history tables and get historical snapshots.
In order to store your username "dog" with Hibernate Envers, you would need to merely implement a custom RevisionEntity that contains your userName field and set it. You can find more information on how to configure the necessary components for this here.
I am trying to model a transient operations solution schema in Hibernate and I am unsure how to get the object graph and behavior I want from the model.
The table structure uses a correlation table (many-to-many) to create lists of users for the operation:
Operation OperationUsers Users
op_id op_id user_id
... user_id ...
In modeling the persistent class Operation.java using hibernate annotations, I created:
#ManyToMany(fetch=FetchType.LAZY)
#JoinColumn(name="op_id")
public List<User> users() { return userlist; }
So far, I have the following questions:
When a user is removed from the list, how do I avoid Hibernate
deleting the user from the Users table? It should just be removed
from the correlation table, not the Users table. I cannot see a valid
CascadeType to accomplish this.
Do I need to put anything more in the method body?
Do I need to add more annotation arguments?
I am expecting to do this without futzing with the User class.
Please tell me that I do not have to mess with User.java!
It's possible I'm overthinking this, but that's the nature of learning... Thanks in advance for any help you can offer!
From the documentation:
Hibernate defines and supports the following object states:
*Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).
*Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.
*Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.
As explained in this answer, you can detach your entity using Session.evict() to prevent hibernate from updating the database or simply clone it and make the needed changes on the copy.
It turns out that the specific answer to my primary question (#1 and the main topic) is: "Do not specify any CascadeType on the property."
The answer is mentioned sorta sideways in the answer to this question.
I am starting to use JPA and I always get confused with the term of entities and their usage, I have read a lot but I still don't quite get it.
I read the Oracle documentation of it but it does not really explain its role in the transaction.
What are JPA enities? does they actually hold the data for each row, I mean, are they stored instances that hold the row data? or they just map tables of the db and then insert and delete in them?
for example if I use this:
entity.setUserName("michel");
Then persisting it, then changing the user name, and persisitig it again (i.e merging it)
Does this change the previously entered user name? or does it create a new row in the db?
An Entity is roughly the same thing as an instance of a class when you are thinking from a code perspective or a row in a table (basically) when you are thinking from a database perspective.
So, it's essentially a persisted / persistable instance of a class. Changing values on it works just like changing values on any other class instance. The difference is that you can persist those changes and, in general, the current state of the class instance (entity) will overwrite the values the row for that instance (entity) had in the database, based on the primary key in the database matching the "id" or similar field in the class instance (entity).
There are exceptions to this behavior, of course, but this is true in general.
It's a model. It's a domain object that can be persisted. Don't over think it. Akin to a Rails model. And remember, models (in this paradigm) are mutable!
I am working on a web application. We are using Hibernate as ORM in our project. Actually, our application creates some tables dynamically based on user selection. The user can select table name, column name and then s/he can import data from a csv file. So my question is: how to map this dynamically created table with Hibernate and Java objects?
It can be done dynamically, but it's somewhat messy:
You'll need to dynamically alter Hibernate's Configuration object before SessionFactory is built. If you're using Spring, this can be done by overriding postProcessAnnotationConfiguration() method of AnnotationSessionFactoryBean; otherwise you'll just need to do it using your Configuration object prior to invoking buildSessionFactory() on it.
If you need to do this without application restart, you're looking at either rebuilding your SessionFactory (which means your users will have to wait until that's done) or using a separate SessionFactory instance specifically dedicated to your custom classes (which is next to impossible if your custom classes need to reference your built-in classes).
You can get access to class / table mappings via configuration.getMappings(). You will then need to create a new table mapping via Table API and add it to configuration via addTable(). Same thing will have to be done with PersistentClass which represents a class mapping. If you're using the same class to represent multiple entities (e.g. map multiple tables) make sure to use unique entity names for each. You'll have to do this (alter the configuration) on every app restart.
How much of the tables are dynamically created? Are the tables similar and you just change the database name?
Here is a discussion of changing the table name:
http://www.experts-exchange.com/Programming/Languages/Java/J2EE/Frameworks/Spring/Q_24237099.html
If you are completely building a new table, can you use a view, and just direct people to a view?
Why are you using Hibernate for this, rather than just dynamically creating queries in JDBC?
The database solution - you can create a view and point it to one table or another (assuming the structure is identical).
CREATE VIEW HIBERNATE_NAME
as
SELECT * FROM TABLE_A
or
CREATE VIEW HIBERNATE_NAME
as
SELECT * FROM TABLE_B
You would need you application to execute native SQL (DDL),
however this should be easier than Hibernate hacks
I have an entity that has a state table associated with it. The state table is managed by another process, and contains a list of objects that my business logic must process. I would like to get a new snapshot of the state table each time I reload the entity. How can I ensure that no part of Hibernate or its support libraries ever caches any of the values of this table? Basically, I want to get a new view of the collection every time I call getMyStateValues ().
Most of the point of Hibernate is to prevent that from happening and return a consistent view of an entity's state in the scope of a given transaction. So either reload the whole entity, in different transactions every time. Or, if you need to reload the state table during a business transaction, load only the state table by the parent entity's id in a separate Hibernate session.
You can create a method in your entity that queries the database and return the collection. getXYXReload(). It´s not a very nice design decision, thought.
You can use Hibernate's CacheMode. It allows you to instruct a hibernate session on how to interact with the cache. You can get access to the underlying session with:
#PersistenceContext EntityManager manager;
...
org.hibernate.Session session = (Session)manager.getDelegate();
Unfortunately, this technique applies to the whole session, and not specifically to an entity.