Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
My Java application is using JPA for object persistence. The business domain is very simple (just three classes are persistent, with 3-5 properties in each). Queries are simple as well. The question is which approach I should use: JPQL or Criteria API?
I'm pretty sure this has already been covered here on SO but I couldn't find the existing question. So, here is my point of view on the question:
I find JPQL queries easier to write/read.
I find the Criteria API nice for building dynamic queries.
Which is basically what you'll find in Hibernate: Criteria vs. HQL.
But there is one major difference between the JPA 2.0 Criteria API and the Hibernate's Criteria API that is worth mentioning: the JPA 2.0 Criteria API is a typesafe API and thus gives compile time checks, code completion, better refactoring support, etc.
However, I don't find that the benefits outweighs the ease of use of JPQL.
To sum up, I would favor JPQL, except for dynamic queries (e.g. for multi criteria search features).
Related questions
Hibernate: Criteria vs. HQL
What are some of the real world example where JPA2 Criteria API is more preferable?
More resources
Hibernate Querying 102 : Criteria API
I answered a similar question previously and I will re-post my answer here for the benefit of the community. I'm going to assume you are using an Application Server vis-a-vis my answer below.
The Criteria API exists to allow for the construction of dynamic SQL queries in a type-safe manner that prevents SQL injection. Otherwise you would be concatenating SQL strings together which is both error prone and a security risk: i.e. SQL Injection. That would be the only time you would want to use the Criteria API.
If the query remains basically the same but need only accept different parameters you should use annotated #NamedQueries which are simpler, precompiled, can be cached within the secondary cache and possibly validated during server startup.
That's basically the the rule of thumb concerning Criteria Queries versus #NamedQueries. In my experience rarely do you require the Criteria API but it is good that it exists for those rare times it is required.
Hope this helps.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Why do we require native SQL in hibernate when we have HQL
can anyone explain with example
There are different dialects for each database. If you use native sql you can query using the dialect of a specific database. Sometime this is not possible using hql.
As an example you can use JSONB type in postgres that is a data type storing jsons. You can create queries accessing the content of this jsonb field that is not accessible with standard hql.
As an example the following query:
SELECT info -> 'customer' AS customer FROM orders;
select the property customer in the json stored in the field info. This has not equivalent in hql.
HQL is internally converted to SQL. SQL is the standard way to communicate with SQL Database.
HQL was created to help Java developers in writing SQL. Hibernate internally take cares of this conversion.
And each database has some specific functions which can not be used with HQL (for example Postgres database uses some extensions like PostGIS which has specific methods) and some complex queries are also very tough to write with HQL.
Writing below query with HQL is almost impossible (although with some external JARs that can done in workaround way, but not as simple as this one)
SELECT ST_AsText(ST_TRANSFORM(ST_GeomFromText(:geometry), :transformation, :toSrid))
HQL implements just a small subset of SQL. This small subset is very useful for CRUD-type operations, but little more than that.
SQL on the other hand has a full feature set of strategies and operators that are of no interest to HQL. When a query requires a more-than-trivial solution, the typical workaround is to avoid HQL and use "native SQL" instead.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have a monolithic app that does the following logics:
Get a list A (Customer) from database
Validate data in A using some criteria, if it's not validated, throw an error
Do some operations on A to get a list B (e.g. Regional customers)
Do sth with B
Now I am transforming my app using microservices, but I have trouble in designing the calls.
As B can be deduced from A entirely, I want to just make a single micro service getCustomerA that returns all the dataset A. That means a single database access is needed. That will be a performance plus.
But the problem is, the operations on A to retrieve list B is also part of the business code. So it's more logical to put these codes in Customer microservice side, if we follow domain driven design, in microservice Customer, maybe getRegionalCustomer.
So I want to know, what is the best practice in this case ? Should we priotize the single database call (first case) or it's better to do two calls (but in this case, 2 database calls) ?
Since this is mainly opinion based I can only give you that :-)
From my experience splitting the app into microservices just for the sake of doing it puts technical dogma over technical simplicity and often introduces a lot of unnecessary overhead.
With regard to the database calls I can also tell you from experience that quite often you win performance when doing two simple calls over doing one overly complex one. Especially if you start introducing big joins over many tables or - ouch - subselects in the on clause.
See if the most simple solution works and keeps the code tidy. Constantly improve quality and optimize when the need for it arises. If you have a piece of logic that warrants to be split of into a microservice (e.g. because you want to use a different language, framework or want to offload some calculations) then go for it.
Domain driven design does not tell that each boundle context only can contains one entity, in fact, a bounded context (or microservice) can contains more than one entity when these entites are clearly related, in other words, when they need to be persisted transactionally.
In your case, due to the tight relation between the two entites, the best way is to build only one microservice that do both operations
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a couple of years of programming experience in Java (Android) and this is my first time with the use of API's to retrieve JSON data. So to get basic facts on a queried topic I thought of using Freebase API however this is now going to be deprecated and Google is moving it to Wikidata. However the query API is still in beta and I simply cannot understand the query API documentation or how to retrieve the facts. So is there an alternative to Wikidata and Freebase?
These are my final questions:
Can someone please explain to me how I would go about using the Wikidata query API? AND retrieve the facts in a readable format?
Or can someone suggest me a better alternative to Freebase other than Wikidata?
The data you want to access is stored in a Subject Property(also Predicate) Object (SPO) format. That means you have a subject and an object that is associated with a property for example <Albert_Einstein> <wasBornIn> <Germany>.
Usually you can access those SPO-databases over an endpoint using SPARQL. SPARQL is a SQL like language which allows you to formulate queries to access the data. Fortunatly for you Wikidata also has a sparql endpoint you can use: https://query.wikidata.org/
Here is a simple example which will load all subjects that are referenced, using a rdf-schema label, to the String "Titanic" and limit the results to 100 entries.
select distinct ?a where {?a <http://www.w3.org/2000/01/rdf-schema#label> "Titanic"#en } LIMIT 100
To query Wikidata in Java you can use Jena which will allow you to use SPARQL-queries and the endpoint to access the data.
As far as I know you can also access Wikidata using http but there a few benefits using SPARQL. There are two other big databases I know of that you can use and both of them have a SPARQL endpoint. So it's quite easy to change the endpoint to access the other two databases. It's also possible that one database contains a reference to another database which you can follow to gather more data.
Since you also asked for alternatives the two databases I mentiond are
DBpedia (SPARQL-Endpoint) and Yago (SPARQL-endpoint). Both use Wikipedia to extract facts and therefor they are huge. Yago also uses WordNet to build a nice taxonomy you can use to classify your data. DBpedia on the other hand has a lot of references to other sites you can use.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I need to persist objects and I want to keep my data classes as clean as possible. The persisted classes do not feature any business-logic code, but only data with getters/setters.
I'm currently implementing a solution with the Observer pattern. Each time an Observable persisted object is modified, it fires a message to an Observer object that takes care of persistence. This way, the only constraint for the persisted object is to be "Observable". It keeps things clean.
Another solution (maybe better?) would be to implement some DAO pattern, and I'm not very aware of the way it works. Maybe it would look like persistedObject.save(); or persistedObject.readById(id);. But it means I would have to define some DAO interface and then to implement the read/create/update/delete method in each and every persisted class
There are many, many, many answers to this question, data serialization or persistence is a core problem in software engineering. Options include using databases, memory mapped files, binary and textual formats, and more.
My personal favorite for quickly persisting objects is GSON, however your use case will dictate what works best for you.
You mention wanting design patterns for persisting Java objects, and while such patterns are approximately as numerous as there are libraries, here are a couple general suggestions:
Use immutable objects
Use the transient keyword for any fields that are not necessary to reconstruct an object
Avoid defining sanity checks or otherwise limiting the range of acceptable values in your objects - an instance constructed from a deserialize call may not correctly trigger your checks, allowing possibly invalid objects to be constructed
Use your serializable objects to construct more complex objects if you need more sanity checking, e.g. serialize a StubPerson POJO, and have a Person object that can be constructed from a StubPerson only as long as the stub's values are valid
I don't know if it fits for you but since you have only bean classes you could use the Java persistence api.
The DAO pattern is the best one to manage data access and persistence as it has been designed specifically for that.
Considering your needs you will probably have to couple it with some factory pattern in order to manage the different implementations (persistence adapters).
I don't know your requirements but if your application can be used by many persons at the same time you will have to care about concurrent accesses and define a policy (transaction, locking, etc... otherwise people will overwrite data each others).
Regarding your question i'd suggest JDO (with data nucleus as implementation) but the learning curve may be too expensive for your effective needs.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am writing my persistent classes for a Java EE 6 project.
I am seeking best practices in writing these classes.
For example, i know that adding version field is recommended.
I am waiting for your help. Merci
UPDATE 1:
I am writing classes for an ecommerce: persons, products, reviews ....
That really depends on what are the requests.
Adding fields just because it is "recommended" may hurt performance, as they are mapped to columns at DB.
Maybe your flow does not require "versioning" at all?
What I would like to suggest for you is (if you insist on using JPA/Hibernate) is:
A. Think of your business logic entities - for example, if this is an application for a library, entities may be - Book, Author, Shelf, Room, Librarian, Reader, and so on...
B. Model the relationships between these entities - For example - a Book may be written by several author. Each other may write several books
Once you're done with this Java/OOP modelling, move on and intorduce relationships, based on JPA annotations:
For example, for the above book author relationship you will need the #ManyToMany annotation.
At this point you will also need to define what are your primary key columns.
You should also consider whether an entity which is used once per each other entity instance - for example - an Address will be used once per Reader, should be kept in a separate table, having OneToOne annotation, or will you prefer to keep it at the Reader table, using an Embeddable class.
However, the best practice can really change when it comes to the domain of the application, the required performance and the use cases.
I would suggest you to start building/designing your application and ask more specific questions.
If you are using JPA in your application, you should need to understand EntityManager and Relationships at least. See this link to learn the usages of JPA. It may be helpful for you.