How to distinguish normal sql query and joining query using jsqlparser? - java

I was trying to get all the details of a sql query. If I provide the query "SELECT a,b FROM TAB1 INNER JOIN TAB2 ON TAB1.a=TAB2.b WHERE a>5", then its working fine. But when it's "SELECT a,b FROM Tab" then it throws exception "java.lang.NullPointerException".
The corresponding code is,
public class ParseJSQLService implements ParseJSQLServiceInterface
{
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
#Override
public QueryDetails parseSqlDetails(QueryDetails queryDetails) throws JSQLParserException
{
CCJSqlParserManager parserManager = new CCJSqlParserManager();
String sql=queryDetails.getQueryText();
Statement statement=parserManager.parse(new StringReader(sql));
String joinType="";
if(statement instanceof Select)
{
Select selectstatement=(Select) statement;
System.out.println(selectstatement);
PlainSelect plainSelect=(PlainSelect) selectstatement.getSelectBody();
String fromItems=plainSelect.getFromItem().toString();
String fieldItems=plainSelect.getSelectItems().toString();
System.out.println("fromItems====>"+fromItems);
System.out.println("fieldItems====>"+fieldItems);
List tableList=tablesNamesFinder.getTableList(selectstatement);
System.out.println(tableList.size());
System.out.println(tableList.toString());
joinType=plainSelect.getJoins().toString();
System.out.println("joinType====>"+joinType);
}
}

The problem is that JSQLParser finds in your second SQL no joins. Therefore plainSelect.getJoins() delivers null. Thats why plainSelect.getJoins().toString() throws a NullPointerException. A slightly modification will make your code work with the second SQL as well.
if (plainSelect.getJoins() != null) {
joinType = plainSelect.getJoins().toString();
System.out.println("joinType====>" + joinType);
}

Related

Replace multi appearance in sql statement using jsqlparser

I am using jsqlparser to parse a SQL string and replace table names in the string.
My input is
SELECT id, test
FROM test1 JOIN test2
ON test1.aa = test2.bb
WHERE test1.conf = \"test\"
LIMIT 10"
and my goal output is
SELECT id, test
FROM test1_suffix
JOIN test2_suffix
ON test1_suffix.aa = test2_suffix.bb
WHERE test1_suffix.conf = \"test\"
LIMIT 10"
And I managed to replace table name by extend the TablesNamesFinder, but it gave me this:
SELECT id, test
FROM test1_suffix
JOIN test2_suffix
ON test1.aa = test2.bb
WHERE test1.conf = \"test\"
LIMIT 10
I say that's half of the job done, but how can I do the rest of my job?
So here is a complete (hopefully) example to replace all occurances of table names. The problem is, that JSqlParser does not differ between aliases and table names. There has to be some logic to skip aliases of your sqls, if you do not want to correct those.
The usage of TableNamesFinder does not do the full job, because it traverses the AST only as far as it is needed to find table names and stops then. That is why my example uses the deparsers.
This code transforms
select id, test from test where name = "test"
to
SELECT id, test FROM test_mytest WHERE name = "test"
and
select * from t2 join t1 on t1.aa = t2.bb where t1.a = "someCondition" limit 10
to
SELECT * FROM t2_mytest JOIN t1_mytest ON t1_mytest.aa = t2_mytest.bb WHERE t1_mytest.a = "someCondition" LIMIT 10
I think that solves your problem.
public class SimpleSqlParser24 {
public static void main(String args[]) throws JSQLParserException {
replaceTableName("select id, test from test where name = \"test\"");
replaceTableName("select * from t2 join t1 on t1.aa = t2.bb where t1.a = \"someCondition\" limit 10");
}
private static void replaceTableName(String sql) throws JSQLParserException {
Select select = (Select) CCJSqlParserUtil.parse(sql);
StringBuilder buffer = new StringBuilder();
ExpressionDeParser expressionDeParser = new ExpressionDeParser() {
#Override
public void visit(Column tableColumn) {
if (tableColumn.getTable() != null) {
tableColumn.getTable().setName(tableColumn.getTable().getName() + "_mytest");
}
super.visit(tableColumn);
}
};
SelectDeParser deparser = new SelectDeParser(expressionDeParser, buffer) {
#Override
public void visit(Table tableName) {
tableName.setName(tableName.getName() + "_mytest");
super.visit(tableName);
}
};
expressionDeParser.setSelectVisitor(deparser);
expressionDeParser.setBuffer(buffer);
select.getSelectBody().accept(deparser);
System.out.println(buffer.toString());
}
}
Add an alias when parsing that gets used instead of the table name.
SELECT *
FROM test a
WHERE a.conf = 'something'
Then this should be changed to, that is the where clause can be the same
SELECT *
FROM test_suffix a
WHERE a.conf = 'something'

"WITH" SQL query not working java

I am using "with data as" as in below query. When I run this in sql developer, it's executing fine, but in java code when I call the query as normal string or through jdbc template in xml configuration file, it gives me bad SQL grammar. Is there any alternative to the below query?
public class NppGWOrphanMessageDao extends DefaultDao {
String sql = "same sql as i posted"
private String replayGWOrphanMsgSQL;
public void setReplayGWOrphanMsgSQL(String replayGWOrphanMsgSQL) {
this.replayGWOrphanMsgSQL = replayGWOrphanMsgSQL;
}
public String getReplayGWOrphanMsgSQL() { return replayGWOrphanMsgSQL; }
public List<Map<String, Object>> getReplayList(HashMap<String, Object> epoch) {
return retrieveAll(replayGWOrphanListSQL, params);
return retrieveAll(sql, epoch); }
}
WITH DATA AS (
SELECT GLOB.ID, GLOB.CHARACTERS
FROM GW_LOB_STORE GLOB
WHERE
NOT EXISTS(SELECT 1 FROM GW_NPP_MSG_INTEGRITY M WHERE M.LOB_STORE_ID=GLOB.ID)
AND NOT EXISTS(SELECT 1 FROM GW_NPP_SAFE_STORE S WHERE S.LOB_STORE_ID=GLOB.ID)
AND NOT EXISTS(SELECT 1 FROM GW_POISON_LOG P WHERE P.LOB_STORE_ID=GLOB.ID)
AND GLOB.CREATED_TS > = :epoch)
SELECT
A.ID AS "GLOBID",
INQUEUEDTL.ID AS "INQUEID",
A.CHARACTERS AS "REQUESTBODY",
INQUEUEDTL.ENDPOINT_ID AS "ENDPOINTID",
INQUEUEDTL.HEADER AS "HEADERS"
FROM DATA A, GW_IN_QUEUE_DETAIL INQUEUEDTL
WHERE A.ID=INQUEUEDTL.ID;
For the sake of completeness:
The problem with this query is the ; at the end of it.
Oracle JDBC driver does not handle it well.

How to build SELECT query with sqlbuilder?

I am using Java and SQLBuilder from http://openhms.sourceforge.net/sqlbuilder/ and am trying to build SQL SELECT query dynamicly:
SelectQuery sql = new SelectQuery();
sql.addAllColumns().addCustomFromTable("table1");
sql.addCondition(BinaryCondition.like("column1", "A"));
However, it creates string like this:
SELECT * FROM table1 WHERE ('column1' LIKE 'A')
Because of wrong quotes ('column1') it doesn't work properly. I suppose it expects some Column object in .like() method.
Is there any way to create query with proper quotes?
I've found a solution. I had to create new class Column that extends CustomSql and pass my column name as parameter:
public class Column extends CustomSql {
public Column(String str) {
super(str);
}
}
And then:
SelectQuery sql = new SelectQuery();
sql.addAllColumns().addCustomFromTable("table1");
sql.addCondition(BinaryCondition.like(new Column("column1"), "A"));
Or without creating own class:
SelectQuery sql = new SelectQuery();
sql.addAllColumns().addCustomFromTable("table1");
sql.addCondition(BinaryCondition.like(new CustomSql("column1"), "A"));
It creates following SQL query, which works fine:
SELECT * FROM table1 WHERE (column1 LIKE 'A')
BinaryCondition.like() takes Object which is a Column Object and then it is converted to SqlObject using Converter.toColumnSqlObject(Object) internally . There is a method named findColumn(String columnName) and findSchema(String tableName) in Class DbTable and Class DbSchemarespectively where you can pass a simple String Object. Try this it would solve your problem:
DbTable table1= schema.findSchema("table1");
DbColumn column1 = table1.findColumn("column1");
SelectQuery sql = new SelectQuery();
sql.addAllColumns().addCustomFromTable(table1);
sql.addCondition(BinaryCondition.like(column1, "A"));
Please, check the working example and refactor your own query
String query3 =
new SelectQuery()
.addCustomColumns(
custNameCol,
FunctionCall.sum().addColumnParams(orderTotalCol))
.addJoins(SelectQuery.JoinType.INNER, custOrderJoin)
.addCondition(BinaryCondition.like(custNameCol, "%bob%"))
.addCondition(BinaryCondition.greaterThan(
orderDateCol,
JdbcEscape.date(new Date(108, 0, 1)), true))
.addGroupings(custNameCol)
.addHaving(BinaryCondition.greaterThan(
FunctionCall.sum().addColumnParams(orderTotalCol),
100, false))
.validate().toString();
Look at this library JDSQL (It requires Java 8):
JQuery jquery = new JQuery();
Collection<Map<String, Object>> result = jquery.select("tbl1::column1", "tbl2::column2") //Select column list
.from("Table1" , "TB1") // Specifiy main table entry, and you can add alias
.join("Table2::tb2") // Provide your join table, and another way to provide alias name
.on("tbl1.key1", "tbl2.key1") // your on statement will be based on the passed 2 values equaliy
.join("Table3", "tbl3", true) // Join another table with a flag to enable/disable the join (Lazy Joining)
.on("tbl2.key2", "tbl3.key1", (st-> {st.and("tbl3.condition = true"); return st;}))
.where("tbl1.condition", true, "!=") // Start your where statment and it also support enable/disable flags
.and("tbl2.condition = true", (st-> {st.or("tbl.cond2", 9000, "="); return st;})) // And statment that is grouping an or inside parentheses to group conditions
.and("tbl3.cond3=5", false) // And statment with a flag to enable/disable the condition
.get((String sql, Map<String, Object> parameters)-> getData(sql, parameters)); // Passing the hybrid getter.
//You can also assign the getter at the jqueryobject itself by calling setGetter.
}
private static Collection<Map<String, Object>> getData(String sql, Map<String, Object> parameters){
return null;
}
}

Select last entity inserted with hibernate

I'm trying to fetch the last entity that was inserted into the database, which I thought would be a very simple thing to do, but every query i try results in some sort of exception to get thrown
The code im using is:
#Override
public DataStoreMark getLastMark() {
String selectQuery = "from Mark";
Query query = em.createNativeQuery(selectQuery, DataStoreMark.class);
try {
return (DataStoreMark) query.getSingleResult();
} catch (NoResultException e) {
log.error("Couldn't find any Marks in the DataStore.");
}
return null;
}
This code however throws a PesistenceException:
org.hibernate.exception.SQLGrammarException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from milestone' at line 1
And there is definitely a record in the database.
Any ideas?
You can use either of createQuery() and createSqlQuery() if it does not work:
1.
String selectQuery = "from Mark";
Query query = em.createQuery(selectQuery);
return (DataStoreMark) query.list().get(0);
2.
String selectQuery = "select * from Mark";
SQLQuery query = (SQLQuery) em.createSQLQuery(selectQuery);
query.addEntity(DataStoreMark.class);
return query.list();
I think hibernate does not tell about last entity added to the database. Alternatively you can write the query specific to your db and run it using createSqlQuery() as shown above.

Problem with getting query result from database

I made a class called SpecializationBean which has two private fields:
private ArrayList<SelectItem> specializationItems= new ArrayList<SelectItem>();
private String specializationName;
I have ofcourse a getter and setter for those two.
and a buildSpecializationList method which builds the specializationItems list: (I call this method in the getter):
public void buildSpecializationList(){
List<Object[]> specializations = null;
try{
Session mySession = HibernateUtil.getAdmSessionFactory().getCurrentSession();
Transaction transaction = mySession.beginTransaction();
String sql = "SELECT J_Specialization_ID, Specialization_Name_Ar FROM J_Specialization WHERE J_Department_ID = '1000001'";
Query query = mySession.createSQLQuery(sql).addScalar("id", Hibernate.LONG).addScalar("name", Hibernate.STRING);
specializations = query.list();
}
catch(Exception e){
e.printStackTrace();
}
this.specializationItems = new ArrayList<SelectItem>(90);
for(Object[] sp: specializations ){
this.specializationItems.add(new SelectItem(sp[0],(String) sp[1]));
}
}
The problem is that I get a null pointer exception which shows that the list specializations (defined in the buildSpecializationList()) is null. I have tried the query myself on the table and it returns a result. I also tried HQL query (istead):
String sqlQuery = "Select JSpecializationId, specializationNameAr FROM JSpecializationWHERE JDepartmentId = '1000001'";
Query q = mySession.createQuery(sqlQuery);
But still, I get a null pointer exception which shows that the query returns me null result. Do you have any suggestions?
For anyone who encounters this problem using Hibernate ...... creating a new class and rewriting the whole thing may actually solve the problem!!!

Categories

Resources