like clause in spring jdbc - spring

#Override
public List<String> getusers(String role) {
// TODO Auto-generated method stub
String namecount = "SELECT userName FROM users WHERE userName LIKE ?";
role="\"%" + role + "%\"";
List<String> names = jdbcTemplate.query("SELECT userName FROM users where userName like ?", new RowMapper() {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
return resultSet.getString(1);
}
},role);
System.out.println(names);
return names;
}
I am not understanding why I am get this error , please can one say where it went wrong
Error message:
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT userName FROM users userName like ?]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'like '%blabla%'' at line 1

You forget the WHERE keyword in the JdbcTemplate query.

Related

Using H2 alias for mocking stored procedure which has output parameters. Is this even possible with H2?

I have created an H2 alias function which is being called when I execute the corresponding spring jdbc StoredProcedure.
public static ResultSet dao_cashflow_read(Integer contractId, Integer contractVersion, Date rateDtmDate, String refSrc,
String rateStatus, String rateType, String message, Integer rowCount) throws SQLException, IOException {
File f = new File(FixingDaoIT.class.getResource("/").getFile().concat("csv/ldn/fixing.csv"));
return new Csv().read(new FileReader(f), null);
}
This part is working as expected as the associated row mapper function parses the result set correctly and generates the entity objects. The problem is, the JdbcTemplate class then attempts to extract the associated output parameters that were registered with the StoredProcedure implementation. Which in turn calls the method below in class JdbcCallableStatement.java
private JdbcResultSet getOpenResultSet() throws SQLException {
try {
checkClosed();
if (resultSet == null) {
throw DbException.get(ErrorCode.NO_DATA_AVAILABLE);
}
if (resultSet.isBeforeFirst()) {
resultSet.next();
}
return resultSet;
} catch (Exception e) {
throw logAndConvert(e);
}
}
This call fails as the resultSet reference is now null and it throws the DbException NO_DATA_AVAILBLE
If I run the application against Sybase, the output params are as expected. Is this an issue with H2 not supporting output params?

Derby DB: Table/View doesn't exist ERROR 42X05

I installed a Derby DB and I opened a connection named "MyDbTest".
I created a table named BOOK for "MyDbTest" connection by the SQL command:
CREATE TABLE BOOK(ID INT, DESCRIPTION VARCHAR(20), UNITCOST VARCHAR(20), ISBN VARCHAR(20), NBOFPAGES INT);
I ran the Derby server by using the command: "startNetworkServer.bat"
I ran the following code (using Open JPA):
public class Main {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("\n\n>>> Executing : " + Main.class.toString() + " <<<\n");
persistBook(new Book(new Long(5000), "H2G2", "Best IT Scifi Book", new Float(12.5), "1234-5678-5678",
new Integer(247)));
Book book = findBook(new Long(5000));
System.out.println("# " + book);
}
/**
* Gets a database connection
*/
static {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:derby://localhost:1527/MyDbTest;create=true", "app", "app");
}
/**
* Persists the book to the database
*/
private static void persistBook(Book book) throws SQLException {
String query = "INSERT INTO BOOK (ID, TITLE, DESCRIPTION, UNITCOST, ISBN, NBOFPAGE) VALUES (?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = getConnection().prepareStatement(query)) {
stmt.setLong(1, book.getId().longValue());
stmt.setString(2, book.getTitle());
stmt.setString(3, book.getDescription());
stmt.setFloat(4, book.getUnitCost().longValue());
stmt.setString(5, book.getIsbn());
stmt.setInt(6, book.getNbOfPage().intValue());
stmt.executeUpdate();
}
}
}
and I got an Error:
Exception in thread "main" java.sql.SQLSyntaxErrorException:
Table/View 'BOOK' does not exist.
Caused by: ERROR 42X05: Table/View 'BOOK' does not exist.
I also read the solution proposed in this post: Is it necessary to create tables each time you connect the derby database?.
Unfortunately, none of them helped me.
I changed "jdbc:derby://localhost:1527/MyDbTest;create=true" to "jdbc:derby://localhost:1527/MyDbTest;create=false"
I don't use "in-memory" configuration in Derby.
I don't think I connect to the DB as another user (I'm not sure about it. How can I check it?).
I had this error because I was using the database name in the SELECT statement instead of the name of the table.

Getting IncorrectResultSetColoumnCount exception in queryForList

I am using queryForList to get a list from DB ,
my code looks like,
List<RoleIdBean> role = jdbcTemplate.queryForList(query , new Object[] {userId},RoleIdBean.class);
query = select * from role where userid=?
role table has two coloumns and roleIdBean has two variables .
When I am running this code it is saying expected 1, actual 2
Could someone please check where i am going wrong and assist how to use this method.
As M. Deinum mentions, you have to provide implementation of RowMapper interface so that Spring knows which columns from your table to map to which properties of your object (RoleIdBean). For instance like this:
List<RoleIdBean> list = jdbcTemplate.query("SELECT * FROM role_id", new Object[]{ userId }, new RowMapper<RoleIdBean>() {
#Override
public RoleIdBean mapRow(ResultSet rs, int rowNum) throws SQLException {
RoleIdBean bean = new RoleIdBean();
// Set properties from the ResultSet, e.g:
// bean.setRole(rs.getString(1));
return bean;
}
});

Spring JdbcTemplate and oracle arrayofnumber

I'm using Spring and Oracle database in my solution and i need to execute script
select count(1) from ELEMENTS, table(cast(? as arrayofnumbers)) session_ids
where root_session_id in session_ids.VALUE
but i have a problem with passing input parameter.
i try to pass List or array of BigInteger into
JdbcTemplate.queryForObject("select count(1) from ELEMENTS, table(cast(? as arrayofnumbers)) session_ids
where root_session_id in session_ids.VALUE", Integer.class, INPUT_PARAMS)
but has an Exception:
java.sql.SQLException: Invalid column type
at oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:8861)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:8338)
at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:9116)
at oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:9093)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:234)
at weblogic.jdbc.wrapper.PreparedStatement.setObject(PreparedStatement.java:357)
Does anyone have the same problem?
EDIT:
Forget to describe arrayofnumber. It's custom type:
TYPE arrayofnumbers as table of number(20)
Found the solution:
final BigInteger[] ids = new BigInteger[]{BigInteger.valueOf(9137797712513092132L)};
int count = jdbc.query("select count(1) from NC_DATAFLOW_ELEMENTS\n" +
" where root_session_id in (select /*+ cardinality(t 10) */ * from table(cast (? as arrayofnumbers)) t)"
, new PreparedStatementSetter() {
public void setValues(PreparedStatement preparedStatement) throws SQLException {
Connection conn = preparedStatement.getConnection();
OracleConnection oraConn = conn.unwrap(OracleConnection.class);
oracle.sql.ARRAY widgets = oraConn.createARRAY("ARRAYOFNUMBERS", ids);
preparedStatement.setArray(1, widgets);
}
}, new ResultSetExtractor<Integer>() {
public Integer extractData(ResultSet resultSet) throws SQLException, DataAccessException {
resultSet.next();
return resultSet.getInt(1);
}
});
out.println(count);
should note that type of array (ARRAYOFNUMBER) should be in upper case

Postgres Parameter Query for SimpleJdbcTemplate

I am trying to execute a parameter query for a Postgre database using Springs SimpleJdbcTemplate. My class that calls the query looks like this:
public class GeoCodeServiceImpl extends SimpleJdbcDaoSupport implements GeoCodeServiceInterface {
public static final String SELECT_STATEMENT = "SELECT ste_code, ste_code_type, name, fips_code " +
"FROM \"steGeo\" " +
"WHERE st_contains( the_geom, ST_GeomFromText('POINT(:lon :lat)',4269))";
public List<GeoCode> getGeoResults(Double lon, Double lat) throws DataAccessException {
MapSqlParameterSource mappedParms = new MapSqlParameterSource("lon", lon.toString());
mappedParms.addValue("lat", lat.toString());
SqlParameterSource namedParms = mappedParms;
List<GeoCode> resultList = getSimpleJdbcTemplate().query(SELECT_STATEMENT, new GeoCodeRowMapper(), namedParms);
if (resultList == null || resultList.size() == 0) {
logger.warn("No record found in GeoCode lookup.");
}
return resultList;
}
protected static final class GeoCodeRowMapper implements RowMapper<GeoCode> {
public GeoCode mapRow(ResultSet rs, int i) throws SQLException {
GeoCode gc = new GeoCode();
gc.setCode(rs.getString(1));
gc.setType(rs.getString(2));
gc.setFips(rs.getString(3));
gc.setName(rs.getString(4));
return gc;
}
}
}
I am testing the query with this class:
public class GeoCodeServiceTest {
public static void main(String[] args) {
Double lat = 40.77599;
Double lon = -83.82322;
String[] cntxs = {"project-datasource-test.xml","locationService-context.xml"};
ApplicationContext ctx = new ClassPathXmlApplicationContext(cntxs);
GeoCodeServiceImpl impl = ctx.getBean("geoCodeService", GeoCodeServiceImpl.class);
List<GeoCode> geoCodes = impl.getGeoResults(lon, lat);
System.out.println(geoCodes);
}
}
I keep getting the following error:
2011-03-07 08:16:29,227 [main] DEBUG org.springframework.jdbc.support.SQLErrorCodesFactory - SQL error codes for 'PostgreSQL' found
2011-03-07 08:16:29,227 [main] DEBUG org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator - Unable to translate SQLException with SQL state 'XX000', error code '0, will now try the fallback translator
2011-03-07 08:16:29,227 [main] DEBUG org.springframework.jdbc.support.SQLStateSQLExceptionTranslator - Extracted SQL state class 'XX' from value 'XX000'
Exception in thread "main" org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [SELECT ste_code, ste_code_type, name, fips_code FROM "steGeo" WHERE st_contains( the_geom, ST_GeomFromText('POINT(:lon :lat)',4269))]; SQL state [XX000]; error code [0]; ERROR: parse error - invalid geometry
Hint: "POINT(" <-- parse error at position 6 within geometry; nested exception is org.postgresql.util.PSQLException: ERROR: parse error - invalid geometry
Hint: "POINT(" <-- parse error at position 6 within geometry
It looks like my parameters are not populated.
I haven't used Postgre before so any help would be much appreciated.
Thanks
Parameters are not handled inside quoted strings, so I guess you need to pass the whole string as a single parameter:
public static final String SELECT_STATEMENT =
"SELECT ste_code, ste_code_type, name, fips_code " +
"FROM \"steGeo\" " +
"WHERE st_contains( the_geom, ST_GeomFromText(:pt, 4269))";
...
MapSqlParameterSource mappedParms = new MapSqlParameterSource("pt",
"POINT(" + lon.toString() + " " + lat.toString() + ")");

Resources