Manage #NamedNativeQuery and schema - jpa

I have many EntityManager, one per schema that I have (I use entity-mappings file to map EMs with schemas). It works.
When I use #NamedQuery it's working like a charm but when I use #NamedNativeQuery schema is not used. I have to qualify with it SELECT foo FROM schema.table.
Is it the right behaviour ?
I think it's not possible to parameter #NamedNativeQuery to dynamically pass schema (I believe only columns can be dynamics not tables or schemas or anything else) so how can I use #NamedNativeQuery with dynamic schema please ?

Prefix your table name with "{h-schema}", e.g.SELECT foo FROM {h-schema}table
(courtesy of getting hibernate default schema name programmatically from session factory?)

Excerpts from documentation :
NamedNativeQuery : Specifies a named native SQL query. Query names are scoped to the persistence unit.
NamedQuery : Specifies a static, named query in the Java Persistence query language. Query names are scoped to the persistence unit.
It isn't specified directly that NamedNativeQuery is static, but both are same scoped & can't be altered afterwards & it's the desired behaviour.
Named queries are mean to be accessed by multiple modules - application wide, identified by unique name, so they are static & constant. You can try building a query string dynamically & can create a native query from it, instead of named native query.

Related

Entity Framework query based on string stored in configuration file

i would like to know if you have any idea how i can achieve this, considering a query stored as string in the configuration file.
I tried to use SqlQuery applied to the DBSet, but the problem is that SqlQuery requires me to select all properties of the required entities in my query. If i don't consider any column, it will complain because is not able to map the query to the entities.
I don't want to select all properties of the entities i want to query.
Thanks
If you are using EF then why not use Database.ExecuteSqlCommand()? It's in the System.Data.Entity namespace.
For example:
int result = db.Database.ExecuteSqlCommand("Non SELECT SQL etc...");
Well, I ended up implementing a mechanism using reflection that basically receives a group of fields to select, and constructs dynamic objects with those fields, so when applied the query with the joins between the entities, will only bring the fields I am looking for.
So, considering Entity1, Entity2, Entity3 with the following relationship
<b>Entity1</b>{
<br/> Entity1Name, <br/> List<*Entity2*> Entity2Items, <br/> etc..
<br/>}
and
<b>Entity2</b> { <br/> Entity2Name, <br/> List<*Entity3*> Entity3Items <br/>}
I can store e.g. the following query in the configuration file, and retrieve the information:
"Entity1.Entity1Name", <br/>
"Entity1.Entity2Items.Entity2Name", <br/>
"Entity1.Entity2Items.Entity3Items.Entity3Name"
Anyway, I was just trying to see if there would be any solution out-of-the-box that would require minimal code changes.
Thank you.

JPA: Map a group of table columns extracted by native query to entity

I know that it is possible using #SqlResultSetMapping but I want to select not whole entity from the database but some fields and then map i to my entity using one of the constructor which accept that fields. Is that possible to map result with #EntityResult for only a few #FieldResult? I was trying to do that and all the time I get error which said that there is not specify mapping for some fields which exist in that entity.
The disadvantage of #SqlResultSetMapping is that you have to select all the columns.
The alternate way of doing this manually iterate over the DB result and populate your objects.
Well, if you are using JPA 1.0 your only option (not considering the manual mapping, of course), is to use #SqlResultSetMapping and map the whole table columns. With JPA 2.1 you can add a javax.persistence.ConstructorResult (see docs here) to map only the needed columns.

SQLAlchemy & postgres reflection: erroneously reflecting all schemas

I have my reflection configured like so:
meta = MetaData()
meta.reflect(bind=db.engine, schema='web')
Base = automap_base(metadata=meta)
Base.prepare()
I thought the schema keyword would limit the reflection to the specified schema, but running the app I see that it reflects tables in all schemas anyway, which leads to some conflicts given I have tables of the same name in different schemas. So Base.classes will contain the wrong classes given that it uses the wrong schema.
What are my options here?
You can limit the tables reflected in MetaData.reflect using the only keyword.
meta.reflect(bind=db.engine, schema='web', only=tables)
If you don't know the tables in the particular schema ahead of time, you can use an Inspector object to get them.
insp = reflection.Inspector.from_engine(db.engine)
tables = insp.get_table_names(schema='web')

How to use Entity, Mapper, Service and Hydrator in ZF2

I am making a ZF2 app. I am using entities, mappers and services (e.g. UserEntity, UserMapper, UserService) to manage the objects/models. Properties in the entities are CamalCased (e.g. FirstName, LastName) while in the database, fields are using underscore (first_name, last_name). I will plan to use a hydrator to map the properties and db-fields when retrieving or saving. The service object (UserService) will be used to communicate with the mapper to retrieve and save data models using the mapper. The hydrator will convert the result of mapper and convert them into proper entities.
The thing I am confused is that when the service (UserService) need to provide some cirteria - for example to find all users with a specific 'last name', will the service use the database field names (last_name) or entity properties name (LastName)?
If the db field name is used in the Service, so any change in the db structure will require me to update the service also, which completely fails the reason of using the whole approach.
If you take a look at the ClassMethods:hydrate method (https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/Hydrator/ClassMethods.php) you will see that it just copies the properties from one object to another. You have the option of converting the property names to/from camelCase but that's it.
If you change a column name in your database then you will need to change corresponding property name in your object. And vice versa. Which I believe is the crux of your question?
If you want to make table column names be independent of your method names then you need something that lets you define an actual mapping table somewhere. Change a column or method name and you only need to update the configuration mapping table.
Not a ZF2 expert so I could be wrong but it doesn't look like any of the supplied hydrators support this.
I do know that Doctrine 2 supports it.

Adding OrderBy clause to a named query

Is it possible to add an OrderBy clause in to JPA Named query at runtime?
Named queries are processed by the persistence provider when the EntityManagerFactory is created. You can't change/modify/append anything about a named query dynamically at runtime.
If you are using JPA 2.0 and you need a way to do high-performance dynamic queries at runtime, you should look into the Criteria API.
From Java EE 5 Documentation : "Is used to specify a named query in the Java Persistence query language, which is a static query expressed in metadata. Query names are scoped to the persistence unit".
As it says, it is static & you can't change the query at runtime.
Rather use custom query or if ordering element is fixed then you can use annotation;
Field:
#OrderBy(value="nickname")
List<Person> friends;
Method:
#OrderBy("nickname ASC")
public List<Person> getFriends() {...};
Even if you can't add order-by clause to your named query, you can provide a parametric orderBy. The following is a perfectly valid query:
SELECT u FROM User u ORDER BY :orderBy
And you are going to change ordering with something like:
query.setParameter("orderBy", "id");