Bad SQL grammer jdbcTemplate spring boot - java

I am getting a bad SQL grammer error when trying to run this.
public List<UserTemp> findByID(Integer PatientNumber) {
String sql = "SELECT PatientNumber,FirstName,Surname from paitents WHERE 'PatientNumber' = ?,PatientNumber";
return jdbcTemplate.query(sql,
(rs, rowNum) ->
new UserTemp(
rs.getInt("PatientNumber"),
rs.getString("FirstName"),
rs.getString("Surname")
));
}
I am trying to select a patient based on the PatientNumber

Is your table called paitents or patients?

Related

org.h2.jdbc.JdbcSQLException: Table not found

I'm getting this exception:
org.h2.jdbc.JdbcSQLException:
Table "CUSTOMERS" not found; SQL statement:
SELECT * FROM CUSTOMERS
This is the H2 Console. I have created a table there:
I have the application.yml file. I have tried to add DB_CLOSE_DELAY=-1 and DATABASE_TO_UPPER=false as well:
spring:
database:
url: jdbc:h2:mem:testdb
h2:
console.enabled: true
Also, I have a configuration class, where I have created the H2 Embedded Database:
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}
Finally, the query. The table is named CUSTOMERS:
public List<Customer> getAll() {
return jdbcTemplate.query("SELECT * FROM CUSTOMERS", (resultSet, rowNum) -> {
Customer customer = new Customer();
customer.setId(resultSet.getLong("id"));
customer.setName(resultSet.getString("name"));
customer.setAge(resultSet.getInt("age"));
return customer;
});
}
What should I do?
I had the same concern as you for a few days.
I solved it by adding this:
;TRACE_LEVEL_FILE=3;TRACE_LEVEL_SYSTEM_OUT=3
ie : jdbc:h2:mem:testdb;TRACE_LEVEL_FILE=3;TRACE_LEVEL_SYSTEM_OUT=3
It helps to know why H2 has a problem.
Usually it is a keyword problem.
You can ignore it by using NON_KEYWORDS : https://www.h2database.com/html/commands.html#set_non_keywords

Hazelcast jet data loading

I'm trying to load database data into hazelcast jet map instance
public void sourceStage(JetInstance jet, Pipeline pipeLine){
SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
dataSource.setDriver(new org.postgresql.Driver());
dataSource.setUrl("jdbc:postgresql://localhost/development");
dataSource.setUsername("postgres");
dataSource.setPassword("root");
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql1 = "SELECT id1 , id2 FROM public.tbl_data where name='india'";
jdbcTemplate.query(sql1, new RowMapper<Object>() {
#Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
jet.getMap("t1").put(rs.getString("id1"), rs.getString("id2"));
return null;
}
});
}
and again trying to use same map as source in the pipe line
pipeLine.readFrom(Sources.map("t1")).map(map -> {
System.err.println(map.getKey() + "---" + map.getValue());
return map;
}).writeTo(Sinks.logger());
and I see I'm not able to read the data as source.
but if check jet.getMap("t1").size()
I'm getting the size value.
To load database data please use a pipeline with the JDBC source and IMap Sink. Mixing both to a single stage breaks the parallel execution model of the Jet engine.

Cannot capture XML returned by SQL Server stored procedure using Java

I am trying to run a SQL Server 2014 stored procedure from Java (Spring) code and get some xml results.
When I run this in a SQL client e.g. RazorSQL I get a bunch of xmls (which is expected because the there are multiple stored procedures within it, that returns those xml).
Here is the Exec call from my SQL client:
EXEC [dbo].[sp_GetType]
#TRAN_ID = 42
#QUAL_ID = 0
GetType does a RETURN 0 at the end (so basically if all steps succeed, it returns 0)
This opens multiple tabs in my client with the xmls.
And one example stored procedure within GetType has these lines:
SELECT TOP 1 ModifiedBy = CASE WHEN #IS_ID = 1 FROM TABLE23.dbo.TRX
TrxId WITH (NOLOCK) WHERE #DD_ID = #TRAN_ID
FOR XML AUTO, ELEMENTS
My goal is to capture all the xmls returned by GetType into a List of objects.
Here is my dao:
private final JdbcTemplate jdbcTemplate;
#Autowired
public TransactionDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
#Transactional(readOnly = true)
public List<Object> getTransaction(Integer tranId, Integer qualId) {
Object dt = new Object();
List<Object> resultList = (List<Object>) jdbcTemplate.execute(
new CallableStatementCreator() {
public CallableStatement createCallableStatement(Connection con) throws SQLException {
String storedProc = "{call sp_GetType(?,?)}";
CallableStatement cs = con.prepareCall(storedProc);
cs.setInt(1, tranId);
cs.setInt(2, qualId);
return cs;
}
}, new CallableStatementCallback() {
public Object doInCallableStatement(CallableStatement > cs) throws SQLException,
DataAccessException {
List<Object> results = new ArrayList<Object>();
cs.execute();
if(cs.getMoreResults())
{
ResultSet rs = cs.getResultSet();
while(rs.next()) //rs has only one record
{
InputStream in = null;
Clob clob = rs.getClob(1);
in = clob.getAsciiStream();
}
rs.close();
}
return results;
}
});
return resultList;
}
I'm using the jtds 1.3.1 driver (I tried connecting using mssql-jdbc but no luck).
Any help is much appreciated.

call procedure with out parameters in hibernate3

I work with hibernate3 and didn't use JPA
I have a procedure in oracle which return 2 out parameter
For test I execute this procedure in oracle with this query.
declare
req_type number;
req_seq number;
begin
insert_req(1111,req_type,req_seq);
dbms_output.put_line('req_type='||req_type);
dbms_output.put_line('req_seq='||req_seq);
end;
Now I want to call this procedure using hibernate
I try with native query without success using this code :
public void insertReq(String numEmp) {
int req_type ;
int req_seq;
String sql = " insert_req(1111,:in1,:in2) ";
SQLQuery query = session.createSQLQuery(sql);
query.setParameter("in1", req_type);
query.setParameter("in2", req_seq);
List results = query.list();
System.out.println(req_type);
System.out.println(req_seq);
}
when I have a function I can run it using hibernate using this code as an example :
public void insertOrder(String numEmp) {
String query = "call insert_order(" + numEmp + ",50)";
SQLQuery sqlQuery = this.getSession().createSQLQuery(query);
sqlQuery.executeUpdate();
}
but the problem is how to call procedure with 2 out parameter using hibernate.
you have to use CallableStatement and registerOutParameter.
you can get a connection from your hibernate session and create the callablestatement.
hibernate does not provide a mecanism to deal with this (at least as i know).
i hope that helps.
Try this and let me know.
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Session session = em.unwrap(Session.class);
session.doWork(new Work() {
#Override
public void execute(Connection con) throws SQLException {
// do something useful
try (CallableStatement stmt = con.prepareCall("{call my_sp()}")) {
stmt.execute();
}
}
});
em.close();
Best regards.

How to convert hql to sql and apply filters on it?

I call this method to convert hql query to sql:
public String toSql(String hqlQueryText) {
if (hqlQueryText != null && hqlQueryText.trim().length() > 0) {
QueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
SessionFactoryImplementor factory = (SessionFactoryImplementor) sessionFactory;
QueryTranslator translator = translatorFactory.createQueryTranslator(hqlQueryText, hqlQueryText, Collections.EMPTY_MAP, factory, null);
translator.compile(Collections.EMPTY_MAP, false);
return translator.getSQLString();
}
return null;
}
and I have this filter in .hbm.xml file of domain class:
<filter name="userAuthorize" condition="some sql query here" />
but I don't know how I should tell hibernate to apply this filter when converting from hql to sql.
Assume that I call above method like this:
public Session getSession() {
try {
return sessionFactory.getCurrentSession();
}
catch (Exception e) {
}
return sessionFactory.openSession();
}
public List<DomainClass> getAll() {
String hql = " some hql query ";
Session session = getSession();
String sql = toSql(hql);
return session.createSQLQuery(sql).list();
}
Not a great Idea. But maybe It helps.
HQL and SQL have some differences, for instance with join , 'on' is used in SQL and 'with' is used in HQL.
So maybe you can use list of words that are unique to HQL and check for them in your String using
hql.contains("with") or hql.indexOf("with").
It is not the responsibility of the QueryTranslator to apply filters. Also, filters don't get applied to native SQL.
It looks like you just want to execute the HQL query? There is no need to have it translated to SQL first:
public List<DomainClass> getAll() {
String hql = " some hql query ";
return session.createQuery(hql).list();
}

Categories