How to build SELECT query with sqlbuilder? - java

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;
}
}

Related

How to get the MySQL query results into a ArrayList<object>

I have SQL query which results in multiple columns. I want to execute this query and get the results into my ArrayList<> instead of the ResultSet.
My class for the column definitions is
public class Record{
private String FileName;
private String FileID;
private String Loan;
private String Page;
}
Query is :
String query = "SELECT FileName, FileID, loanNumnber, PageNumber FROM table";
ResultSet rs = stmt.executeQuery(query);
I want the results of the query in recordData object.
ArrayList<Record> recordData = new ArrayList<Record>;
Please suggest how the arraylist can be populated directly with correct mapping.
Use following code snippet if you want to implement by yourself. It will convert the result set to Record objects and add it to the ArrayList.
Record record;
while(rs.next()){
record = new record();
String fileName = rs.getString("FileName");
String fileID = rs.getString("FileID");
String loanNumnber = rs.getString("loanNumnber");
String pageNumber = rs.getString("PageNumber");
record.setFileName(fileName);
record.setFileID(fileID);
record.setLoan(loanNumnber);
record.setPage(pageNumber);
recordData.add(record)
}
rs.close();
Otherwise, if you want to use any third party frameworks then there are lot of options such as Hibernate, iBatis etc.
You can use the mybatis.
Please use the ORM.
https://en.wikipedia.org/wiki/Object-relational_mapping
You should use OR mapper like Hibernate. Thanks POJO classes you can do whan you want.
Some readings:
http://www.tutorialspoint.com/hibernate/hibernate_examples.htm
http://www.mkyong.com/tutorials/hibernate-tutorials/
Add parenthesis "()" to this line in your code so that it looks like this:
ArrayList<Record> recordData = new ArrayList<Record>();

Casting string to enum after getting string by column from database

I have Condition entity and have one attribute ConditionType who have two enums, medical and behavioral, that I want to set after getting CONDITION_NAME from SQL Server.
#SuppressWarnings("rawtypes")
private List<Condition> getConditions(String patientId, Date runDate) {
// TODO
JdbcTemplate template = new JdbcTemplate(dataSource);
String sql = "select patient_id,condition_name from patient_condition, cpl_manage_condition"
+ " where patient_condition.condition_id = cpl_manage_condition.condition_id";
List<Map<String, Object>> rows = template.queryForList(sql);
List<Condition> conditions = new ArrayList<Condition>();
for (Map row: rows) {
Condition condition = new Condition();
//getting error
condition.setType((ConditionType)((String)row.get("CONDITION_NAME")));
conditions.add(condition);
}
return conditions;
}
I'm assuming your error is
condition.setType((ConditionType)((String)row.get("CONDITION_NAME")));
And should be
condition.setType(ConditionType.valueOf(row.get("CONDITION_NAME").toString()));
See also this question.
If ConditionType is an enum, you can use ConditionType.valueOf(String) to convert a String value to that type. Notice you should take care of null and invalid arguments then.

How to handle 'IN' case in SQL Statement with the way of Parameterized Query?

To avoid SQL injection attacks in my project, I'm attempting access database with Parameterized Query way. Right now I know how to handle equal case like below (With Spring JdbcTemplate):
String sql = "SELECT * FROM T_USER WHERE USERNAME = ? AND PASSWORD = ?"
jdbcTemplate.query(sql,
new UserRowMapper(),
new Object[]{"%admin%", "%password%"});
Above code runs no problem, but I had no idea how to handle the 'IN' case, following is my case, and it works failed:
String sql =
"SELECT * FROM T_USER WHERE USERNAME = ? AND PASSWORD = ? AND CLASS_ID IN (?)"
jdbcTemplate.query(sql,
new UserRowMapper(),
new Object[]{"%admin%", "%password%", "1,2,3"});
Anybody give me guidance? Thanks a lot.
I think you can create a List and pass it as 3rd parameter. Also You need to use LIKE in place of = in first two column filters.
List<Integer> classIds = new ArrayList<Integer>();
classIds.add(1);
classIds.add(2);
classIds.add(3);
String sql = "SELECT * FROM T_USER WHERE "+
"USERNAME LIKE ? AND PASSWORD LIKE ? AND CLASS_ID IN (?)";
jdbcTemplate.query(sql, new Object[]{"%admin%", "%password%", classIds},
new UserRowMapper());
Please note: Here is the syntax:
public List query(String sql, Object[] args, RowMapper rowMapper)
throws DataAccessException
EDIT: Please try namedParameterJdbcTemplate as bwlow:
String sql = "SELECT * FROM T_USER WHERE "+
"USERNAME LIKE :uname AND PASSWORD LIKE :passwd AND CLASS_ID IN (:ids)";
Map<String, Object> namedParameters = new HashMap<String, Object>();
namedParameters.put("uname", "%admin%);
namedParameters.put("passwd", "%password%");
namedParameters.put("ids", classIds);
List result = namedParameterJdbcTemplate.query(sql, namedParameters,
new UserRowMapper());
Three options:
Generate different JDBC queries for each length of the IN LIST, and parameterize each INDIVIDUAL item, e.g. this answer
For small tables, you can cheat and use a LIKE statement, e.g. this answer
Use a SPLIT function (anti-LISTAGG) to turn the delimited list into individual rows of one column each, and JOIN against it. Example SPLIT function
You'll parameterize the argument to the function as a single string

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

I was wondering if there is a more elegant way to do IN() queries with Spring's JDBCTemplate. Currently I do something like that:
StringBuilder jobTypeInClauseBuilder = new StringBuilder();
for(int i = 0; i < jobTypes.length; i++) {
Type jobType = jobTypes[i];
if(i != 0) {
jobTypeInClauseBuilder.append(',');
}
jobTypeInClauseBuilder.append(jobType.convert());
}
Which is quite painful since if I have nine lines just for building the clause for the IN() query. I would like to have something like the parameter substitution of prepared statements
You want a parameter source:
Set<Integer> ids = ...;
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);
List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
parameters, getRowMapper());
This only works if getJdbcTemplate() returns an instance of type NamedParameterJdbcTemplate
I do the "in clause" query with spring jdbc like this:
String sql = "SELECT bg.goodsid FROM beiker_goods bg WHERE bg.goodsid IN (:goodsid)";
List ids = Arrays.asList(new Integer[]{12496,12497,12498,12499});
Map<String, List> paramMap = Collections.singletonMap("goodsid", ids);
NamedParameterJdbcTemplate template =
new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());
List<Long> list = template.queryForList(sql, paramMap, Long.class);
If you get an exception for : Invalid column type
Please use getNamedParameterJdbcTemplate() instead of getJdbcTemplate()
List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
getRowMapper());
Note that the second two arguments are swapped around.
Refer to here
write query with named parameter, use simple ListPreparedStatementSetter with all parameters in sequence. Just add below snippet to convert the query in traditional form based to available parameters,
ParsedSql parsedSql = NamedParameterUtils.parseSqlStatement(namedSql);
List<Integer> parameters = new ArrayList<Integer>();
for (A a : paramBeans)
parameters.add(a.getId());
MapSqlParameterSource parameterSource = new MapSqlParameterSource();
parameterSource.addValue("placeholder1", parameters);
// create SQL with ?'s
String sql = NamedParameterUtils.substituteNamedParameters(parsedSql, parameterSource);
return sql;
Many things changed since 2009, but I can only find answers saying you need to use NamedParametersJDBCTemplate.
For me it works if I just do a
db.query(sql, new MyRowMapper(), StringUtils.join(listeParamsForInClause, ","));
using SimpleJDBCTemplate or JDBCTemplate

PreparedStatement not returning ordered ResultSet

I am having some problems and I'm sure it's something stupid.
So I have a query like
SELECT name, id, xyz FROM table ORDER BY ?
then later down the road setting the ? doing a
ps.setString(1, "xyz");
I am outputting the query and the value of xyz in the console. When I loop through the ResultSet returned from the PreparedStatement the values are not in the correct order. They are in the returned order as if I had left the ORDER BY clause off. When I copy/paste the query and the value into TOAD it runs and comes back correctly.
Any ideas to why the ResultSet is not coming back in the correct order?
The database will see the query as
SELECT name, id, xyz FROM table ORDER BY 'xyz'
That is to say, order by a constant expression (the string 'xyz' in this case). Any order will satisfy that.
? is for parameters, you can't use it to insert column names. The generated statements will look something like
SELECT name, id, xyz FROM table ORDER BY 'xyz'
so that your entries are sorted by the string 'xyz', not by the content of column xyz.
Why not run:
ps.setInteger(1, 3);
Regards.
EDIT: AFAIK Oracle 10g supports it.
PreparedStatement placeholders are not intend for tablenames nor columnnames. They are only intented for actual column values.
You can however use String#format() for this, that's also the way I often do. For example:
private static final String SQL_SELECT_ORDER = "SELECT name, id, xyz FROM table ORDER BY %s";
...
public List<Data> list(boolean ascending) {
String order = ascending ? "ASC" : "DESC";
String sql = String.format(SQL_SELECT_ORDER, order);
...
Another example:
private static final String SQL_SELECT_IN = "SELECT name, id, xyz FROM table WHERE id IN (%s)";
...
public List<Data> list(Set<Long> ids) {
String placeHolders = generatePlaceHolders(ids.size()); // Should return "?,?,?..."
String sql = String.format(SQL_SELECT_IN, placeHolders);
...
DAOUtil.setValues(preparedStatement, ids.toArray());
...
The database will see the query like this
SELECT name, id, xyz FROM table ORDER BY 'xyz'
I think you should add more variable like order_field and order_direction
I assume you have a method like below and I give you an example to solve it
pulbic List<Object> getAllTableWithOrder(String order_field, String order_direction) {
String sql = "select * from table order by ? ?";
//add connection here
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
ps.setString(1,order_field);
ps.setString(2,order_direction);
logger.info(String.valueOf(ps)); //returns something like: com.mysql.jdbc.JDBC4PreparedStatement#a0ff86: select * from table order by 'id' 'desc'
String sqlb = String.valueOf(ps);
String sqlc = sqlb.replace("'"+order_field+"'", order_field);
String sqld = sqlc.replace("'"+order_direction+"'", order_direction);
String[] normQuery = sqld.split(":");
ResultSet result = conn.createStatement().executeQuery(normQuery[1]);
while(result.next()) {
//iteration
}
}

Categories

Resources