Does exists a java library that can create sql statements?
I'm not in search of something fancy, just something at "string manipulation" level: I just use jdbc (with Preparestatements and Resultsets) but I don't really like to pass huge strings containing SQL code...
What I need is a "simple" Select class (or something similar); in my mind all I really want is to be able to do
SQLStatement stat = Select("*").from("table").where("condition and condition").orderby("something");
ResultSet rs = Connection.getResultSet(stat.toString());
/* equals to "select * from table where condition and condition order by something" */
Maybe I'm blind, but I cannot find something like that...
Obviously, I want some methods/class able to write inserts and updates and the other stuff...
I excluded ORMs for two reasons:
the db schema it's "old" and I cannot change it, and I'm not sure how can I adapt the ORM to follow our db
AFAIK the ORMs needs to change the model (maybe adding a base class, maybe you need to implements an interface) and the model in my project is big, old and grumpy
Onestly, I don't really like ORMs: Objects and Set theory just aren't made to be mapped (IMHO)
ORM (Object Relational Mapping) library is the clue.
Hibernate is the most mature one.
And the Hibernate-s Criteria API is object - oriented way to create such queries as You wished. Criteria API doc.
Hibernate is most likely what you're looking for. It contains many advanced features, but SQL statements are more straightforward.
Take a look at their site: http://www.hibernate.org/
I'd also recommend skimming through this guide:
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
Try SQLBuilder project. Honestly, I have not used this. Looking at their docs, i think it might suit your requirement.
You can also try to find similar APIs in Sourceforge,Google code etc..
I am not sure if you use Java for a native application or for the web.
If you use Java for web you could consider using the Play framework.
Easy and has Hibernate included with a really simple implementation (easier when implementing Hibernate yourself).
Related
I am using jOOQ to generate my SQL queries and I was wondering if there is a way to inject a condition in all the queries that my application does.
For example, I would like to have something like account = {accountNameHere} in all the SELECT that the application does. Since I already have a a high number of different queries, I would like to do that without manually adding the condition to each statement.
Is there a way to do that easily using jOOQ ? Maybe using the VisitListener ?
Yes, a VisitListener will be the most thorough way to inject a custom predicate into all of your SELECT statements (including subqueries, of course). In fact, what you're looking for is sometimes referred to as "row level security" (natively supported in RDBMS like Oracle or SQL Server).
The following blog post explains how to achieve this via a VisitListener:
http://blog.jooq.org/2015/06/17/implementing-client-side-row-level-security-with-jooq
I am working in a project which uses JPA ORM and framework provides two kinds of method to create queries.
entityManager.createQuery(query1);
entityManager.createNativeQuery(query2);
I understand the kinds of query string is to be passed to use them, but I don't know exactly why do we need to create native query? Probably we don't want to use ORM capabilities there?
You do not need to create a native query unless you want to. JPQL eventually is translated into SQL by the framework but the framework lets you call the native query also. Why would want to do that:
Low level access, which means that you can optimize and handle the mapping by yourself; with SQL you actually access the database table while with JPQL you access the entity objects;
Maybe you do not want to learn JPQL if you already know SQL
You already have the queries written in SQL, and do not have resources/time to port them to JPQL
createQuery uses JPAs own query language, you select from Class names instead of table names. This is not SQL, it is just similar, and is later transformed to real SQL. Mapping to java classes will be done automatically and actual class instances will be returned as result.
createNativeQuery uses real SQL, and will not be able to use JPA features. This method is used in general if you need to do something really odd that is not supported by JPA. A list of Object[] will be returned, and mapping to java objects will have to be done manually. In other words, its just like working with a DB before JPA came to, just slightly more convenient since connection handling is done automatically.
I have used it for optimization purposes. Using Native queries means that the ORM mapping is not in place, and instead of JPQL, you use the DB's native syntax. So, as #RasmusFranke also pointed out, if you need something that is not supported by JPA (like when you want to use DB vendor specific extensions, which is conceptually a bad idea, since JPA is all about being DB agnostic, but happens nevertheless. I know...)
The other effect of this is that by using native queries, only the supplied query is run. No eager fetching of other entities, or other unwanted stuff. This way, if you deal with huge amounts of objects, you can save some heap space.
We're going to write a new web interface for a big system based on Oracle database. All business rules are already coded in PL/SQL stored procedures and we'd like to reuse as much code as possible. We'll write some new stored procedures that will combine the existing business rules and return the final result dataset.
We want to do this on the database level to avoid java-db round trips. The interface layer will be written in Java (we'd like to use GWT), so we need a way of passing data from Oracle stored procedures to Java service side. The data can be e.g. a set of properties of a specific item or a list of items fulfilling certain criteria.
Would anyone recommend a preferable way of doing this?
We're considering one of the 2 following scenarios:
passing objects and lists of objects (DB object types defined on the
schema level)
passing a sys_refcursor
We verified that both approaches are "doable", the question is more about design decision, best practice, possible maintenance problems, flexibility, etc.
I'd appreciate any hints.
I would recommend sticking with a refcursor with well defined keys (agreed on both sides by java devs and pl/sql developers). This is much easier to extend in the future, you can easily convert the refcursor to hashmap and then a hashmap to a POJO using a apache bean utils if needed. I'm working on a big telecom project with many approaches to this issue and refcursor seems to be the best at the end of the day.
In the past I have achieved exactly the same with classic JDBC CallableStatement without any perfomance or maintenance issues. With ORM solutions like Hibernate making persistence much more flexible, you can wrap your solution around Hibernate as achieve in this post. Also see this example if you are not already familiar with the way store procedure and CallableStatement works.
It's been a while since I've done something like that, but the way I remember is that you need to define a view that calls your stored procedure, and you can then easily read the result sets from within java, with the OR-mapper of your choice.
So, this seems close to your scenario 1, which never caused any problems in my experience.
The one thing one needs to be careful is transaction handling: If your stored procedures write data, and you call several of them within a Java EE transaction, you might get into a situation of data inconsistency.
I just started working on upgrading a small component in a distributed java application. The main application is a rather complicated applet/servlet combo running on JBoss and it extensively uses Hibernate for its DataAccess. The component i am working on however is very a very straightforward data importing service.
Basically the workflow is
Listen for a network event
Parse the data packet, extract a set of identifiers
Map the identifier set to a primary key in our database
Parse the rest of the packet and insert items in a related table using the foreign key found in step 3
Repeat
in the previous version of this component it used a hibernate based DAL, that is no longer usable for a variety of reasons (in particular it is EOL), so I am in charge of replacing the Data Access layer for this component.
So on the one hand I think i should use Hibernate because that's what the rest of the application does, but on the other i think i should just use regular java.sql.* classes because my requirements are really straightforward and aren't expected to change any time soon.
So my question is (and i understand it is subjective) at what point do you think that the added complexity of using an ORM tool (in terms of configuration, dependencies...) is worth it?
UPDATE
due to the way the DataAccesLayer for the main application was written (weird dependencies) i cannot easily use it, i would have to implement it myself.
If we look into why Spring-Hibernate combination is used?
Because for simple Jdbc operation we have to do lot of operation like getting a connection.
Making a statement and handling resultset.For all these steps there are lot of exception handling.
But with spring hibernate you have to use just this:
public PostProfiles findPostProfilesById(long id) {
List list=getHibernateTemplate().find("from PostProfiles where id=?",id);
return (PostProfiles) list.get(0);
}
And everything is taken care by framework.I hope it will solve you dilemma
I think the answer really depends on your skill set. It would probably take similar amount of time to craft a simple solution involving a handful of tables in either way (Hibernate or raw JDBC) if you are comfortable with both techniques.
As I am pretty comfortable with Hibernate, I'd just choose it as I prefer to working in a higher level and not worrying about things that Hibernate handles for me. Yes, it has its own glitches, but especially for simple data models it does the job, and does it well.
The only few reasons why would I choose plain JDBC would be:
uber-complicated maximum-optimized SQL that is performance critical;
Hibernate being stupid and not being capable to express what I want;
And especially if you say you are already managing other entities with Hibernate, why not keep your code in the same style everywhere?
I think you are better off using JDBC api. From what you describe, the two operations (select foreign key from table, insert into table_2) can easily be executed with a simple Stored Procedure call.
The advantage of using this technique is that you can manage transactions/exceptions within your stored procedure call.
Does anyone know of a Java library that provides a useful abstraction for analyzing and manipulating arbitrary relational database schemata? I'm thinking of something that could do things like
LibraryClass dbLib = ...;
DbSchema schema = dbLib.getSchema("my_schema");
List<DbTable> tables = schema.getTables();
and
DbTable myTable = ...
for(DbColumn col : myTable.getColumns()){
... = col.getType();
}
or even manipulate tables like
myTable.addColumn(
new DbColumn("my_new_column", Type.UNSIGNED_INTEGER);
);
DbColumn myColumn = ...
myTable.removeColumn(myColumn);
Most Database modeling tools will have such an abstraction internally, but is there one in Java that I can use, or will I have to roll my own?
JDBC itself has such an abstraction. Look at java.sql.DatabaseMetaData. However, this is an optional part of the standard and it depends on the JDBC driver you are using wether it is implemented or not.
DdlUtils has what you're looking for. You can read/write schemas to/from XML (in Torque format) or a live database, or even define the database schema in pure Java. Better yet, read the on-line doco, it's quite good.
I haven't used it in years but Hibernate used to have tools for manipulating data models at build time. Hibernate also has the notion dialects which would be helpful if you're targeting more than one database vendor.
When I was at MetaMatrix, we built such a thing using EMF (Eclipse Modeling Framework) where we created a representational meta-model in UML, then generated it from code. The nice thing about metamodeling is that if you do it well, you can interoperate things across metamodels, provided you have made good choices against the meta-meta-model.
We also had an importer that would import metadata from the JDBC API and create the appropriate equivalent model objects (database, table, column, keys, etc).
This code might be open source some day since they got bought by JBoss but I don't think it is yet.