DB connection in java--Query in JSP--Is it possible? And how - java

so here is my thought and problem at the same time...
I will create eventually a web app with Netbeans.
I have started by creating the database in POSTGRESQL which is ready and filled.
Anyway, to the point, of my first problem:
I have created a Java class, which manages to create a connection with the database. The method i am using, produces a Connection variable and returns it.
I don't want to make the query in there, BUT in the Jsp page. Is it possible? ALL the examples i have seen, are making the SQL Query in the Java page and not in the JSP page. But i don't want this, cause the queries i will make in the future of my project, will be like...thousands!
In general,i want the Db connection in the Java file and the Queries in jsp files.
What do you think?
thanks

Im pretty sure your question is violating the rules. Whatever.
Did you try NamedQueries? It's some time ago since I last wrote Java or JSP Code but as I understood your question, this should solve your problem.
Here a link
Explanation:
A named query is a statically defined query with a predefined
unchangeable query string. Using named queries instead of dynamic
queries may improve code organization by separating the JPQL query
strings from the Java code. It also enforces the use of query
parameters rather than embedding literals dynamically into the query
string and results in more efficient queries.
Example:
#Entity
#NamedQueries({
#NamedQuery(name="Country.findAll",
query="SELECT c FROM Country c"),
#NamedQuery(name="Country.findByName",
query="SELECT c FROM Country c WHERE c.name = :name"),
})
public class Country {
...
}

Related

How to use native SQL as a fragment (where clause) of a bigger query made with Criteria API in Hibernate?

I have a following problem. In application, which I am developing, we use Hibernate and every query is written with Criteria API. Now, in some places, we want to add possibility for user to write some SQL code which will be used as part of where clause in a query. So basically, user can filter data displayed to him from database in his own way.
For a few days now, I am trying to find a way to modify our previous queries to acquire result described above. Here is what I know:
It looks like you cannot combine Criteria API with native SQL. You can either write whole query in SQL or use only criteria API. Is that right?
I am asking this question because it would be the easiest solution, just to use this SQL code as another predicate in where clause in our query. But I don't think it's possbile on this level.
I know on which table user wants to filter data. So I could just execute native SQL query and use result list as a parameter to IN clause in criteria query. But I don't know if it is efficient with many records in a result list.
So if I cannot do it on criteria API level, I thought that maybe I could somehow influence the SQL generetion process and put my SQL in a proper place but it seems to be impossible.
So my real question is: is it somehow possible to have access to SQL code of the query, after SQL generation phase but before actual execution of query? Just to manipulate with it manually? Can it be done safely and as far as possible simply?
Or maybe just try to parse this SQL written by user and use it in criteria query?
Changing existing criteria queries into native SQL queries is rather out of discussion.
Yes, you can get the SQL from the Hibernate criteria using the org.hibernate.loader.criteria.CriteriaQueryTranslator class.
This will allow you to append the additional SQL clause(s) to the end and execute it as a native SQL:
CriteriaQueryTranslator translator = new CriteriaQueryTranslator(factory, criteria, "myEntityName", CriteriaQueryTranslator.ROOT_SQL_ALIAS);
String select = translator.getSelect();
String whereClause = translator.getWhereCondition();
Personally though, if faced with this requirement I would shy away from accepting SQL from the end-user and give them a user interface to populate some type of filter object. This can then be converted into HQL criterion, which is much safer and doesn't tie your code as tightly to the database implementation.
Edit based on comments
Example of extracting SQL from a JPA query implemented with Hibernate:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<MyEntity> q = builder.createQuery(MyEntity.class);
Root<MyEntity> entity = q.from(MyEntity.class);
q.select(entity).orderBy(builder.desc(entity.get("lastModified")));
TypedQuery<MyEntity> query = entityManager.createQuery(q);
String sql = query.unwrap(org.hibernate.Query.class).getQueryString();
criteria.add(Restrictions.sqlRestriction(" AND ID in (1,2,3)" ));

Selecting individual data_types across mutliple tables using SQL and HQL from Oracle

Hello World, Here is the situation,
Basically instead of generating values from a table like like so
34.324, 09/13/2011, thankyou,
I would like to generate the type of that specific value
e.g
VarChar2, Date, varchar2(char 30)
Just to add another layer of difficulty a Java application pulls data from the multiple Oracle database tables using HQL. Thus I would need an equivalent HQL statement to the SQL statement (if it exists)..
I understand the DESC keyword lists the column data types for an entire table however as mentioned above I require specificity.
In Summary
I would like to reverse engineer this application to generate a report of the data_types of the data instead of the actual data itself. I could easily just manually walk through the code however they are over 200 entries and this will be a real pain.
Any help is truly appreciated. If this question is unclear please let me know and I will provide more details and examples.

sql query into hibernate

I am a beginner at hibernate and have read up a lot but I'm stuck at this one point.
In my JSF app that I'm implementing hibertate, I have this SQL query that works in my database:
SELECT *
FROM CourseProduct
INNER JOIN Course
ON CourseProduct.number=Course.number
inner join Product
on CourseProduct.product=Product.product;
I am trying to do the same thing with hibernate for my JSF application. So far I came up with:
List results = session.createCriteria(Course.class)
.setFetchMode("product", FetchMode.JOIN)
.setFetchMode("number", FetchMode.JOIN)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.list();
Is this correct or completely wrong? Also how do I access the fields from the results (if I even have to do that, since hibernate populates the classes for me)? It seems like the results I get are only the the Course Table, the value of the primary key in Product, but not the other 2 fields in the table Product.
EDIT
I guess I solved my own problem. It looks as though the above code is correct, I just didn't realize that in order to access the class Product I had to access it from the Set in the Course class! I just used an iterator to get the data I need in the get method for the set of Products in the Course class.
I guess I solved my own problem. It looks as though the above code is correct, I just didn't realize that in order to access the class Product I had to access it from the Set in the Course class! I just used an iterator to get the data I need in the get method for the set of Products in the Course class.
Update: I really solved the problem. I just got rid of hibernate. The sql query works fine, got my data using a perpared Statement and the result set using the regular old way (java.sql.DriverManager).
For some reason the hibernate driver didn't even like using my statement as a native SQL (kept giving me an exception trying to convert an Integer). I googled the problem and they say it's a bug in hibernate!

Memcache implementation design

Iam trying to implement memcache in my web application and just wanted to get suggestions that whether what iam doing is right in terms of design.
I have a class SimpleDataAccessor which run all my insert, update and select sql queries. So any query that has to be performed is executed inside the method of this class.
So inside the method where I have my select query implementation i have a method which stores the resultset in memcache like this.
storeinMC(resultset.getJSON(),sqlquery);
the sqlquery here is my key.
Also before running the selectquery i check in memcache that whether I have a resultset already for that query.
if((String res=getRSFromMC(sqlquery)==null)
So i've tried to keep it plain and simple.
Do you see any issues with this.?
As rai.skumar rightfully pointed out your SQL statements could be constructed differently (e.g. WHERE clause could contain same conditions in diff order, etc.)
So to overcome above mentioned issues, you need to parse your SQL and get all the relevant pieces from it. Then you can combine these pieces into a cache key.
You can take a look at SQL parsers: ZQL, JSqlParser, General SQL Parser for Java that return you java classes out of your SQL.
Another option would be to use JPA instead of straight JDBC. For example Hibernate has great JPA support and fully capable of caching your queries.
If you feel closer to JDBC you could use MyBatis that has very JDBC like syntax and caching support.
Consider below queries:
String k1 = "Select * from table"; //Query1
String k2 = "Select * from TABLE"; // Query2 ; notice TABLE is in caps
Both of above SQL queries are same and will fetch same data. But if above queries are used as keys in Memchached they will get stored at different places ( as k1.equals(k2) will return false).
Also if somehow you can ensure that there are no typos or extra spaces, it won't be very efficient as keys/queries could be very big.

Can we write describe table query in JPQL?

I am taking a 'Keyword' and table name from user.
Now, I want to find all the columns of table whose data type is varchar(String).
Then I will create query which will compare the keyword with those column and matching rows will be returned as result set.
I tried desc table_name query, but it didn't work.
Can we write describe table query in JPQL?
If not then is there any other way to solve above situation?
Please help and thank you in advance.
No workaround is necessary, because it's not a drawback of the technology. It is not JPQL that needs to be changed, it's your choice of technology. In JPQL you cannot even select data from a table. You select from classes, and these can be mapped to multiple tables at once, resulting in SQL joins for simplest queries. Describing such a join would be meaningless. And even if you could describe a table, you do not use names of columns in JPQL, but properties of objects. Describing tables in JPQL makes no sense.
JPQL is meant for querying objects, not tables. Also, it is meant for static work (where classes are mapped to relations once and for good) and not for dynamic things like mapping tables to objects on-the-fly or live inspection of database (that is what ror's AR is for). Dynamic discovery of properties is not a part of that.
Depending on what you really want to achieve (we only know what you are trying to do, that's different) you have two basic choices:
if you are trying to write a piece of software in a dynamic way, so that it adjusts itself to changes in schema - drop JPQL (or any other ORM). Java classes are meant to be static, you can't really map them to dynamic tables (or grow new attributes). Use rowsets, they work fine and they will let you use SQL;
if you are building a clever library that can be shared by many projects and so has to work with many different static mappings, use reflection API to find properties of objects that you query for. Names of columns in the table will not help you anyway, since in JPQL queries you have to use names defined in mappings.
Map the database dictionary tables and read the required data from them. For Oracle database you will need to select from these three tables: user_tab_comments, user_tab_cols, user_col_comments; to achieve the full functionality of the describe statement.
There are some talks over the community about dynamic definition of the persistent unit in the future releases of JPA: http://www.oracle.com/goto/newsletters/javadev/0111/blogs_sun_devoxx.html?msgid=3-3156674507
According to me, we can not use describe query in jpql.

Categories

Resources