how to assign different concurrency strategy to the same (persistence) entity? - java

I'm using JPA and I am using second-level cache for all the reference entities.
Everything's working well, I can get the entities from second-level cache is they were already been selected before.
Now, I have two applications, they both use the same database (so they both use the same table, values, etc).
1.The read-only application just read data from database, it doesn't modify the database at all. Therefore, I choose the "READ_ ONLY" concurrency strategy for the second-level cache, aiming at a better performance.
2.The read-write application read and write as well the data of database, it modify the database. Consequently, I have to choose the "READ_ WRITE" or "NONSTRICT_ READ_ WRITE" concurrency strategy for the second-level cache.
However, the concurrency strategy is assigned in the annotation of each entity class, so I cannot change it programatically. (I don't use class mapping files for JPA, so I can't use two mapping files, each for a different concurrency strategy for the same entity class.)
My Question is, is there a good way to change the concurrenty strategy of the second-level cache on the fly according to my 2 different applications?

I have not used Hibernate, but at least if you use JPA it is possible to override even a single annotation with a deployment descriptor file. You should also be able to override also any vendor specific property with the deployment descriptor.
Unfortunately I cannot give you an example but hope this helps you.

So Therefore, I think the current solution is to replace all the annotations of each entities with Hibernate mapping files, so that for different deployment (application as well), we could use different Hibernate mapping files.

Related

Infinispan per entity eviction,lifespan controlling using java annotations

Infinispan has eviction policy, lifespan for specific to entity. From below question we can make the change in persistence.xml.
Infinispan - set per Entity expiration.lifespan
My question is there a way to do this in annotation in that particular entity?
I am not aware of any such config. The reason for the absence of it is probably because Infinispan (and other cache providers) are general-purpose caching frameworks which in general are not aware of Hibernate second-level caching specifics.
On the other hand, again in general, Hibernate and java.persistence do not interfere with specific cache provider implementations and APIs. That means that a cache provider may even not allow defining expiration policy while still being perfectly able to serve as Hibernate L2 cache.
However, you could define your own annotations and set the Infinispan config values programmatically. You could turn it to an interesting open source project, if there are none so far that do similar thing. :)

Resolving Hibernate subtleties

I have spent several days now researching Hibernate and have several small questions about it that in and of themselves don't really merit cluttering SO but I think, together, help give some insight to how Hibernate operates as a whole:
To create a Hibernate entity, one must add a reference to it in the hibernate.cfg.xml config file as well as annotating the respective POJO as being an #Entity. This feels horribly redundant. Why can you just use the annotation and just skip the XML entry?
Hibernate seems to have great built-in support for parameter binding with its Query API, but I see no such options for the Criteria API. Is parameterizing possible with Criteria instances: if so, how, and if not, why?
I see many L2 (2nd level) Cache Providers: EhCache, OSCache, SwarmCache, etc. Is it possible to write your own CacheProvider, throw it on the ruuntime classpath and have Hibernate use your own homegrown cache system (like SLF4J does with logger bindings)?
Thanks in advance!
Because it would force Hibernate to scan all the classes of the classpath to discover annotated classes. And because you might have some entities in the classpath that you don't want to use in your application. Or you might want to have some entities in a session factory, and some others in another one. Or even the same entity in two seperate session factories.
The Criteria API has methods which bind the parameters directly: Restrictions.eq("someProperty", someValue); for example.
It's of course possible to write your own second-level cache, but you would have to configure Hibernate to use it, as you do with all the other providers. Dropping the classes in the classpath is not sufficient.

Does Hibernate have to drive database design?

I spent all of yesterday reading various articles/tutorials on Hibernate and although I am blown-away by how powerful it is, I have one major concern with it.
It seems that the standard practice is to allow Hibernate to design/generate your DB schema for you, which is a new and scary concept that I am choking on. From the tutorials I read, you just add a new entity to your hibernate.cfg.xml config file, annotate any POJO you want with #Entity, and voila - Hibernate creates the tables for you. Although this is very cool, it has me wondering about a handful of scenarios:
What if you already have a DB schema and the one Hibernate wants to generate for you does not conform to it? What if you have a crazy DBA that refuses to budge on the pre-defined (non-Hibernate) schema?
What if you have reference tables with tens of thousands of records in it (like all the cities in the world)? Would you have to instantiate and save() tens of thousands of unique POJOs or is there a way to configure Hibernate so it will honor and not overwrite data already existing in your tables?
What if you want to do perf tuning on your schema/tables? This includes indexing, normalizing above and beyond what Hibernate creates automatically?
What if you want to add constraints or triggers to your tables? Indexes?
I guess at the root of this is the following:
It looks like Hibernate creates and forces a particular schema/config on your DB. I am wondering how this agenda will conflict with our platform standards, our DBA philosophies, and our ability to perf tune/tweak tables that Hibernate interacts with.
Thanks in advance.
I think you're attributing too much power to Hibernate.
Hibernate does have an idiom that may influence database implementation.
Hibernate does not generate a schema for you unless you ask it to do so. It's possible to start with an existing schema and map it to Java objects using Hibernate. But it might not be possible or optimal if the schema conflicts with Hibernate requirements.
If the DBA won't budge - as they shouldn't - or Hibernate can't accomodate you, then you have your answer: you can't use Hibernate.
Your DBA might consent, but your app might find that the dynamic SQL that's generated for you by Hibernate isn't what you want.
Fortunately for you, it's not the only game in town.
I don't think implementations have to be all or none. If you use simple JDBC to access reference data, what's the harm?
Database design considerations should be independent of Hibernate. Constraints, triggers, normalization, and indexes should be driven by business needs, not your middleware choices.
If you don't have a solid object model, or the schema can't accomodate it, then you should reconsider Hibernate. There's straight JDBC, stored procedures, Spring JDBC, and iBatis as alternatives.
Hibernate comes with a default way to map objects to tables - like several tools/libraries, it favours convention over configuration for simplicity.
However, if you want to map the entities to database tables differently, you can explicitly tell Hibernate how these are mapped (from simple attributes such as changing the table name, through to redefining the foreign-key relationships between related entities and how this is persisted).
If you do this correctly, you don't need to instantiate and save existing data, as this would be pointless - the database already contains the information about the entities in exactly the form that Hibernate understands. (Think about it - to load and then immediately save an entity should always be a no-op, and so can be skipped altogether.)
So the short answer to your question is "no". If you don't care for designing tables, you can let Hibernate adopt a reasonable default. If you do want to design your schema explicitly though, you can do this and then describe that exact schema to Hibernate.
As someone who's worked on java and hibernate in the enterprise for a long time, I have seen very few projects which use this capability. You'll see some build tools and other things do this, but for a real enterprise app, i've never seen this.
Most DBA's won't let the application user create tables. They rely on a privileged user to do those things, and the user that the app connects as would have r/w privs on the data but not the schema itself.
As a result, you write the SQL yourself, and you do the hibernate mappings to match. It doesn't mean your object design won't influence your SQL, but you should still always create your schema upfront.
No. You can use hibernate tools to generate the entities from existing database.
There are 2 ways you can go about in using Hibernate. If you have good DBA or database designer, then it is better to design the database and then map it into hibernate.
On the other hand if you don't have DBA and have good developer then let Hibernate generate Database for you.
The concept behind Hibernate is to map Database and the Objects. So it is called as ORM (Object-Relational Mapping) tool.
Read here for Object Relational Impedance.
This is the preferred way for a quick'n dirty prototype or a simple tutorial, but it's far from being the preferred way for any production application. I largely prefer designing the database independently, using scripts to generate the schema, tables, views, indexes, etc., and map the schema to entities.
As long as the mapping finds the tables and columns in the database, everything is fine.
As soon as you have data in your database and the schema must change, you'll have to write migration scripts anyway. You can't just drop everything and restart from scratch. The tutorials are written for developers starting with Hibernate and who must discover Hibernate as quick as possible, without dealing with complex SQL scripts.
What if you already have a DB schema ...
I don't know where you get that impression. Hibernate can use existing schema. It is quite flexible.
What if you have reference tables ...
Make the relationship LAZY, and it won't load automatically. Only changed object will be saved.
What if you want to do perf tuning ...
Just don't use the generated schema. It is just a starting point. You can customize as you need.
What if you want to add constraints or triggers to your tables? Indexes?
Some as above.
You can use hibernate with an existing database schema.
You can use various annotations to map to existing tables and columns, for example:
#Table(name = "dbschema.dbTable") - should be placed before your class file to map it
#Column(name = "colName") - to map a column
Just be sure that the hibernate is configured with this option:
hibernate.hbm2ddl.auto=update
If you set this to create it will create the schema, so do not do this in your case.
Use hibernate/jpa when appropiate. A common practice when designing apps is to extract the draft and alter it manually after needs (indices etc). However, it will be a pain for you if you change the db layout from hibernate way to do things. Lots of the beauty of JPA will be lost. For tasks which require heavy performance tuning and full control - just go for reguar jdbc.
Some answers:
A. It is possible to add an index annotation : see the table annotation.
B. If you have reference tables, you may choose to have lazy fetching or eager fetching (i.e - if your tables represent a person and a its books - whether to load a person without its book, or with its books)
C. Hibernate can be used to work on existing schema. The schema might not be trivial to work with , but as other have said, you should design db only according to business needs, and not according to framework conventions
D. I would like to encourage you also to read what hibernate does "under the hood" - it uses lots of usage of proxies, which hurts performance, you must understand well the scope of session , and the usages of 1st level and 2nd level cache .
E. Following what I wrote at section D - working with triggers will cause your DB to change "under the hood" when it comes to hibernate. Consider a case where updating a record will create (using a trigger) an entry in some archiving table , and let's say this table is also annotated via hibernate - your hibernate caching will not be aware of the change that happend outside of the application scope.
F. It is important to me to state that I'm not against Hibernate, but you should not use it for all solutions, this is a mistake I did in the past. I now work with Spring-JDBC and I'm quite pleased (for our application needs it will be hard to use Hibernate, and I assume we will consider this only in the case we need to support more than one DB flavor).

how to use another implementation for JPA 2 level 2 cache?

We'd like to use another L2 cache for our big JPA application. We are trying to achieve a shared cache between multiple servers.
We use Eclipselink as JPA implementation, and some legacy codes uses internal Eclipselink API's, so switching is not an option.
Coherence/Toplink Grid seems too expensive (4000$/cpu?).
Is there a way we could plug another cache implementation? Is something specified in JPA 2 (I can't find anything in the specs, but maybe I just misread it)? Proprietary (=Eclipselink specific) solutions are ok, as long as they are somewhat documented or simple enough (we don't want that to break).
Is there a way we could plug another cache implementation?
Did you investigate the use of the EclipseLink shared object cache that comes with EclipseLink? Going by the description, the shared object cache is not confined to a single EntityManager alone, and is available across the lifecycles of several Entity managers, i.e. across several transactions. It is of course, constrained to the lifecycle of an EntityManagerFactory, which may be as live as long as the application is running in the container.
The EclipseLink shared object cache is different from Oracle Coherence, and I believe it is not licensed and packaged separately, thereby making it available on all containers.
JPA does not specify a pluggable cache interface. I don't know if it ever will, but if it does, my bet is that it won't be until after the resurrected JSR-107 finishes defining a standard API to object caches, which JPA would then be able to use. It might also have to wait for JSR 347, which is defining another cache interface, whose relationship to JCache is somewhat unclear (there is open factional warfare between and within the groups, with some members of the 107 expert group trying to declare 347 an independent republic, and invade Mexico).
So, until then, you're at the mercy of your provider's cache interface. I am not an EclipseLink expert, but last time i looked, i couldn't see a pluggable second-level cache interface. In fact, i think only Hibernate and, of course, DataNucleus, have them.
Most cache implementations are not distributed (other than Coherence), just local.
EclipseLink already supports a share cache and cache coordination for caching in a cluster.
What cache do you intent to use, and what benefit do you intend to get from it?
EclipseLink does support integration with 3rd party caches, this API was created for the Coherence integration, although Coherence is the only cache that currently provides an integration.

How can I set the schema name used by hibernate entities at query time?

Our application uses Hibernate for ORM, and stores data in several schemas, accessing them with a user whose grants are customized for the application.
The schema names are determined at runtime based on data; it's not feasible to include their names in the entity mapping documents. This means that I need a way to tell Hibernate to use a specific schema name when performing lookups. Is there a way to do this?
Here's a page that lists some ways you can manage multiple schemas in Hibernate. I'd probably go with implementing your own connection provider. You'll probably want to disable caching as well.
We ran into this problem at work. I fixed it, as Robert suggests, by creating a connection provider (ie, an implementation of DataSource), called ""OracleSchemaRemappingDataSource" and using spring to do the plumbing.
Basically, this datasource implements getConnection(). The implementation of that method works by getting a connection from some other data source by spring injection, which it assumes to be an oracle connection, and then executing
ALTER SESSION SET CURRENT_SCHEMA = 'someotherschema'
and them passing that connection back.
All of the hibernate config is careful to use names without specifying schemas for them.
Also: with this, you don't want to disable caching - allow hibernate to manage connections as normal, as we are not doing any magic within the app such as using different connections on a per-user basis.

Categories

Resources