Invalid column type issue with spring JdbcTemplate - spring

I am using spring JdbcTemplate.
public int countCallbackResponse(final int empId, final int noOfDay) {
int callbackCount = getJdbcTemplate().queryForInt(SurveyQuery.COUNT_CALLBACKS,
new PreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, empId);
ps.setInt(2, noOfDay);
}
}, Integer.class);
return callbackCount;
}
Error:
callback][org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [SELECT COUNT(sr.RESPONSEID) FROM EMPSUR s, EMPSURRES sr WHERE s.IEMPID = sr.IEMPID AND sr.IEMPID=? AND TRUNC(sr.TSCREATED) BETWEEN TRUNC(SYSDATE - (? + s.PRIORITY_DAYS)) AND TRUNC(SYSDATE) AND sr.SSTATUS IN ('SUS1','SUS1')]; SQL state [99999]; error code [17004]; Invalid column type; nested exception is java.sql.SQLException: Invalid column type]

Related

nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar

#Override
public int saved(Register r) {
String sql = "insert into tbl_register(fname,lname,email,phone,address,username,password,gender,use)values(?,?,?,?,?,?,?,?,?)";
return JdbcTemplate.update(sql,r.getFname(), r.getLname(), r.getEmail(), r.getPhone(), r.getAddress(), r.getUsername(), r.getPassword(), r.getGender(), r.getUse());
}

SpringBoot+JDBCTemplate+Parent Key not found error

Unable to insert into child table in a single transaction using springboot and jdbctemplate.
Controller:
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public Response addUser(#RequestBody UserVo userVo) throws Exception
{
service.addUserRecord(userVo);
}
Service Layer:
#Autowired
private Dao dao;
#Transactional(readOnly = false)
public void addUserRecord(#RequestBody UserVo userVo) throws Exception
{
int parentSeqNo = dao.addUser();
int result = dao.addUserDetails(parentSeqNo, list);
}
DAOImple class:
#Autowired
private JdbcTemplate jdbcTemplate;
public int addUser()
{
try
{
String sql = "INSERT INTO user_table() VALUES (?,?,?,?,?) ";
jdbcTemplate.update(sql,....);
return seqNo;
}
catch(Exception e)
{
e.printStackTrace();
throw e;
}
}
public void addUserDetails(String seqNo, List<String> list){
String sql="insert into user_details_table values(?,?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
String img = list.get(i);
ps.setString(1, seqNo);
ps.setString(2, img);
}
public int getBatchSize() {
return list.size();
}
});
return;
}
Issue/Error:
ORA-02291: integrity constraint (FK3) violated - parent key not found; nested exception is java.sql.SQLIntegrityConstraintViolationException:
Database tables and constraints are looks good and tried to insert using sql editor, just working fine. While testing from postman tool, getting parent key not found exception. Greatly appreciated for any suggestions on this issue.

spring jdbc insert command

public void save(RegistrationBean registrationBean) throws SQLException {
String first_name = registrationBean.getFirst_name();
String last_name = registrationBean.getLast_name();
String email = registrationBean.getEmail();
String password = registrationBean.getPassword();
String phone = registrationBean.getPhone();
try {
int rows = jdbcTemplate.update("insert into users values(?,?,?,?,?)", first_name, last_name, email,password,phone);
System.out.println("inserted" + rows);
} catch (DataAccessException e) {
System.out.println(" not row inserted.reason : " + e);
}
}
this is my save method it gives sqlerror of org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [insert into users values(?,?,?,?,?)]; nested exception is java.sql.SQLException: Column count doesn't match value count at row 1.
Please anyone help solve the issue.

error while committing the transaction error in spring mvc?

HibernateSpatialJPA class:
public class HibernateSpatialJPA {
private static final EntityManagerFactory emFactory;
static {
try {
emFactory = Persistence.createEntityManagerFactory("org.hibernate.events.jpa");
}catch(Throwable ex){
System.err.println("Cannot create EntityManagerFactory.");
throw new ExceptionInInitializerError(ex);
}
}
public static EntityManager createEntityManager() {
return emFactory.createEntityManager();
}
public static void close(){
emFactory.close();
}
}
this is manager class:
public class SavegeojsonManager {
SavegeojsonEntity theEvent = new SavegeojsonEntity();
public boolean insert(JSONObject json)
{
GeoJSON item = new GeoJSON(json);
return insert(item);
}
public boolean insert(GeoJSON item)
{
boolean success=false;
try {
String vectorType = item.getType();
EntityManager em = HibernateSpatialJPA.createEntityManager();
em.getTransaction().begin();
theEvent.setVectorType(vectorType);
em.persist(theEvent);
em.getTransaction().commit();
em.close();
success=true;
}
catch (Exception ex) {
System.out.println(ex.getMessage());
success = false;
}
HibernateSpatialJPA.close();
return success;
}
}
and this is GeoJsonClass :
public class GeoJSON
{
private int id;
private String type;
private String data;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getType() {return type;}
public void setType(String type) {this.type = type;}
public String getData() {return data;}
public void setData(String data) { this.data = data; }
public GeoJSON() {
}
public GeoJSON(JSONObject json) {
parse(json);
}
public GeoJSON parse(JSONObject json) {
StringWriter out = new StringWriter();
json.write(out);
this.data = out.toString();
this.type = json.getString("type");
try {
out.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
throw new RuntimeException(ex);
}
return this;
}
}
But I am not able to save into database because error :
enter code here : "error while committing the transaction."
Do you have any idea about this error ?
Below is the Exception stack trace:-
javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:92)
at com.springapp.model.SavegeojsonManager.insert(SavegeojsonManager.java:32)
at com.springapp.model.SavegeojsonManager.insert(SavegeojsonManager.java:19)
at com.springapp.mvc.HSpatialController.saveGeoJson(HSpatialController.java:46)
...
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: ERROR: column "vectortype" of relation "savegeojson" does not exist Position: 76 at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377) at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300) at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:80) ... 40 more Caused by: org.hibernate.exception.SQLGrammarException: ERROR: column "vectortype" of relation "savegeojson" does not exist Position: 76 at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122) at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125) at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110) at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129) at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81) at com.sun.proxy.$Proxy26.executeUpdate(Unknown Source) at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2962) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3403) at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88) at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:354) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:275) at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326) at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52) at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1214) at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:403) at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101) at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175) at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:75) ... 40 more Caused by: org.postgresql.util.PSQLException: ERROR: column "vectortype" of relation "savegeojson" does not exist Position: 76 at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2062) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1795) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:479) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:367) at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:321) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122) ... 56 more
You are saving Entity SavegeojsonEntity to postgresql db and this error means:
Caused by: org.postgresql.util.PSQLException: ERROR: column "vectortype" of relation "savegeojson" does not exist
Position: 76
Table that SavegeojsonEntity are mapped to does not have column vectortype. Check in your db that column exists in table.
If it does not exist you need to add that column to table.

Trivial create, insert with jdbctemplate

I'm trying to explore the basics of Spring's jdbctemplate. I'm having trouble with a simple example:
public static void main(String[] args) throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
String url = "jdbc:h2:mem:test";
dataSource.setURL(url);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("create table something (id int primary key, name varchar(100))");
jdbcTemplate.execute("insert into something (id, name) values (1, 'Brian')");
}
Triggers this:
Caused by: org.h2.jdbc.JdbcSQLException: Table "SOMETHING" not found; SQL statement:
insert into something (id, name) values (1, 'Brian') [42102-177]
If I convert that code to use the raw JDBC api, it works fine:
public static void main(String[] args) throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
String url = "jdbc:h2:mem:test";
dataSource.setURL(url);
try (Connection dbConnection = dataSource.getConnection()) {
try (Statement statement = dbConnection.createStatement()) {
statement.execute("create table something (id int primary key, name varchar(100))");
statement.execute("insert into something (id, name) values (1, 'Brian')");
try (ResultSet rs = statement.executeQuery("select id, name from something")) {
while (rs.next()) {
System.out.println(String.format("got result. id=%d. name=%s", rs.getInt(1), rs.getString(2)));
}
}
}
}
}
If it matters, my Gradle dependencies:
compile 'org.springframework:spring-jdbc:4.0.6.RELEASE'
compile 'com.h2database:h2:1.4.177'
please try to use update method instead execute.

Resources