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.
Related
I have a table in Database where datatype of a column(STATUS) is CLOB.I need to read that STATUS
create table STATUS_TABLE
(
STATE_ID number(20,0),
STATUS clob
)
I am trying to read CLOB column as below
String getStatus = "SELECT STATUS FROM STATUS_TABLE WHERE STATE_ID="+id;
Query statusResults = session.createSQLQuery(getStatus);
List statusRes = statusResults.list();
if ((statusRes != null) && (statusRes.size() > 0)) {
oracle.sql.CLOB clobValue = (oracle.sql.CLOB) statusRes.get(0);
status = clobValue.getSubString(1, (int) clobValue.length());
log.info("Status->:" + status.toString());
}
And getting the error as
java.lang.ClassCastException: $Proxy194 cannot be cast to oracle.sql.CLOB
How can i read clob data from DB and convert to String ?
Here is the corrected version, and an explanation appears below the code:
Query query = session.createSQLQuery("SELECT STATUS FROM STATUS_TABLE WHERE STATE_ID = :param1");
query.setInt("param1", id);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
List statusRes = query.list();
if (statusRes != null) {
for (Object object : statusRes) {
Map row = (Map)object;
java.sql.Clob clobValue = (java.sql.Clob) row.get("STATUS");
status = clobValue.getSubString(1, (int) clobValue.length());
log.info("Status->:" + status.toString());
}
}
Problems I saw with your code:
You were building a raw query string using concatenation. This leaves you vulnerable to SQL injection and other bad things.
For whatever reason you were trying to cast the CLOB to oracle.sql.CLOB. AFAIK JDBC will return a java.sql.Clob
You are performing a native Hibernate query, which will return a list result set whose type is not known at compile time. Therefore, each element in the list represents one record.
I would like to fetch serveral rows of data from a table.
I have a dao, sql and some parameters.
public static final String SELECT = ""
+ "SELECT NAME, SURNAME, AGE, LEVEL"
+ "FROM MYTABLE "
+ "WHERE "
public static final String CONDITION = ""
+ "SURNAME = :" + PARAM_SURNAME
+ "AND LEVEL = :" + PARAM_LEVEL;
For retrieval of a signle object I would do something like that:
public MyObject getMyThing(
final String surname,
final Integer level) {
final MapSqlParameterSource parameters = new MapSqlParameterSource()
.addValue(PARAM_SURNAME, surname)
.addValue(PARAM_LEVEL, level);
final String query = SELECT + CONDITION;
return myNamedTemplate.query(query, parameters, new MyObjectRowMapper());
}
And it is be just fine. However I would also like to use one SQL to retrieve several objects from databse. I know about the "IN" clause but it is not good enough as its usage will affect performance in the bad way.
What I would want is something that results in a following query:
SELECT STUFF FROM TABLE WHERE
//and the part I am interested in:
(SURNAME = :PARAM_SURNAME
AND LEVEL = :PARAM_LEVEL)
OR
(SURNAME = :PARAM_SURNAME
AND LEVEL = :PARAM_LEVEL)
OR
(SURNAME = :PARAM_SURNAME
AND LEVEL = :PARAM_LEVEL)
//and so on...
So the question:
How can I achieve this using JDBC Named Template in Spring? I cannot figure out how to do parameter mapping. Desired method in DAO could be something like that:
public List<MyObject> getMyThings(
final List<String> surnames,
final List<Integer> levels) {
final MapSqlParameterSource parameters = // magic
final String query = // more magic
return myNamedTemplate.query(query, parameters, new MyObjectRowMapper());
}
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;
}
}
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>();
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!!!