using sequence in namedparameterJDBCTemplate for insertion into two tables - java

how to use sequence in namedparameterJDBCTemplate for insertion into two tables ?
Database- orcale
springjdbcnamedparametertemplate .
my Dao is looking like this
#Override
public void insert(Message message) {
String SQL = "INSERT into mssg (mssg_id, mssg_text, mssg_channel)"
+ " values (mssg_sequence.nextval,:mssg_text,:mssg_channel)";
String SQLMessage_app = "INSERT into message_app(mssg_app_type,mssg_id)"
+ "values(:mssg_app_type,mssg_sequence.currval)";
namedParameterJdbcTemplate.update(SQL,
new BeanPropertySqlParameterSource(message));
namedParameterJdbcTemplate.update(SQLMessage_app,
new BeanPropertySqlParameterSource(message));
}
oracle tables are these
This is the first table
create table mssg (
mssg_id number(10) NOT NULL,
mssg_text varchar2(25)NOT NULL,
mssg_channel varchar(25)NOT NULL,
constraint pk_mssg_id PRIMARY KEY(mssg_id)
);
Create sequence mssg_sequence
start with 1
increment by 1
minvalue 1
maxvalue 100000;
This is the second table
CREATE TABLE MESSAGE_APP(
mssg_app_type VARCHAR2(25),
mssg_id NUMBER(10),
CONSTRAINT fk_mssg
FOREIGN KEY(mssg_id)
REFERENCES mssg(mssg_id)
ON DELETE CASCADE);
COMMIT;
iam getting this error :
org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL [INSERT
into
message_app(mssg_app_type,mssg_id)values(?,mssg_sequence.currval)];
SQL state [72000]; error code [8002]; ORA-08002: sequence
MSSG_SEQUENCE.CURRVAL is not yet defined in this session ; nested
exception is java.sql.SQLException: ORA-08002: sequence
MSSG_SEQUENCE.CURRVAL is not yet defined in this session
can anybody help me to insert data into two tables by using sequence???
Thanks in advance :)

Related

Create table as select with parameter using jdbcTemplate

I want to use jdbcTemplate to create table based on another table under condition. I have postgres database. When I execute this and pass parameter:
String SQL = "create table test as (select * from users where countryId =?)";
jdbcTemplate.update(SQL, new Object[] {3})
I receive table test with all columns from users table but with no rows.
However, when I execute this:
String SQL = "create table test as (select * from users where countryId =3)";
jdbcTemplate.update(SQL)
I receive test table with rows where countryId = 3, so that is what I was expecting to receive in the first solution.
Your passing of the bind variable is not correct, but it does not play any role.
You simple can not use a bind variable in a data definition statement as you immediately see in the triggered error
Caught: org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL
[create table test as (select * from users where countryId =?)];
SQL state [72000]; error code [1027];
ORA-01027: bind variables not allowed for data definition operations
So you have two options, either concatenate the statement (which is not recommended due to the danger of SQL injection)
or split the statement in two parts:
// create empty table
sql = "create table test as (select * from users where 1 = 0)";
jdbcTemplate.update(sql)
// insert data
sql = "insert into test(countryId, name) select countryId, name from users where countryId =?";
updCnt = jdbcTemplate.update(sql, new SqlParameterValue(Types.INTEGER,3));
Note that in the insert statement you can see the correct way of passing an interger value of 3 as a bind variable.
You can follow below approach as well:-
jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS employee_tmp (id INT NOT NULL)");
List<Object[]> employeeIds = new ArrayList<>();
for (Integer id : ids) {
employeeIds.add(new Object[] { id });
}
jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds);
Here you may query with 2 operations to avoid SQL injection.
You are using method update from jdbcTemplate in a wrong way.
Try with this:
String SQL = "create table test as (select * from users where countryId = ?)";
jdbcTemplate.update(SQL, 3);

Spring JDBC & Oracle DB 12c: java.sql.SQLException: Invalid column type. Why?

I'm struggling with following exception:
org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [update EVALUATION_SHEET set STATUS=?, LAST_EDITED=? where id=?]; SQL state [99999]; error code [17004]; Invalid column type; nested exception is java.sql.SQLException: Invalid column type
Which is thrown here:
jdbcTemplate.update("update E_SHEET set STATUS=?, LAST_EDITED=? where id=?",
new Object[]{eSheet.getStatus().ordinal(), eSheet.getLastEditDate(), eSheet.getId()},
new Object[]{OracleTypes.NUMBER, OracleTypes.TIMESTAMP, OracleTypes.NUMBER});
The database table is created as follows:
create table E_SHEET (
ID number not null unique,
ID_POSITION number not null,
STATUS number default 0 not null,
ID_EXAMINER number not null,
LAST_EDITED timestamp not null);
I have no idea what is causing the problem. This method:
eSheet.getLastEditDate()
returns java.util.Date object. I am using Spring JDBC template with Spring Boot and Oracle DB 12c as a datasource.
after the spring documentation http://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html, an update would work like this:
jdbcTemplate.update("update t_actor set last_name = ? where id = ?", "Banjo", 5276L);
or like this
jdbcTemplate.update("update orders set shipping_charge = shipping_charge * ? / 100 where id = ?", pct, orderId);
But you are passing arrays of Objects as parameters to the method.
Why not just this?
jdbcTemplate.update("update E_SHEET set STATUS=?, LAST_EDITED=? where id=?", eSheet.getStatus().ordinal(), eSheet.getLastEditDate(), eSheet.getId());

Preventing from Multiple primary key error

This is my code for executing in my java program:
public static void createBooksTablesAndSetPK() {
String selectDB = "Use lib8";
String createBooksTable = "Create table IF NOT EXISTS books (ID int,Name varchar(20),ISBN varchar(10),Date date )";
String bookTablePK = "ALTER TABLE BOOKS ADD PRIMARY KEY(id)";
Statement st = null;
try (
Connection con = DriverManager.getConnection(dbUrl, "root", "2323");) {
st = con.createStatement();
st.execute(selectDB);
st.execute(createBooksTable);
st.execute(bookTablePK);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
I cat use IF NOT EXIST for creating databasesand tables to prevent creating duplicate database and tables and corresponding errors.
But i don't know how prevent Multiple primary key error, because program may call createBooksTablesAndSetPK() multiple times.
Error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Multiple primary key defined
The column Book_id is not existing in your case. You are creating a table with ID as the column and then updating the table with a PRIMARY KEY constraint on a column that is not existing.
Create table IF NOT EXISTS books (ID int,Name varchar(20),ISBN varchar(10),Date date )
ALTER TABLE BOOKS ADD PRIMARY KEY(BOOK_id)
Try running these statements on a MySQL command prompt (or MySql Workbench) and the see the error.
You need change the alter table command like this.
ALTER TABLE BOOKS ADD BOOK_id VARCHAR( 255 ), ADD PRIMARY KEY(BOOK_id);

SPRING MVC database error jdbc

Thanks for your time
I am getting an error as my project is having 2 modules add driver and add truck for which i am executing the sql query for both but when i execute the query for addDriver module the database exception is throwing stating
org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO truck(TRegnNo,VendorName,PurchaseDate,Price,RepairDate,InvoiceNo,RepairCost) VALUES(?,?,?,?,?,?,?)]; Column 'TRegnNo' cannot be null; nested exception is com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'TRegnNo' cannot be null
org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:101)
driver insert sql statement public void insertData(Driver driver)
{
String sql = "INSERT INTO driver" + "(DLNo,DName,Age,Experience) VALUES (?,?,?,?)";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql, new Object[] {driver.getLicenseNumber(),driver.getDriverName(),driver.getAge(),driver.getExperience()});
} Truck Insert code public void insertData(Truck truck)
{
String sql = "INSERT INTO truck" + "(TRegnNo,VendorName,PurchaseDate,Price,RepairDate,InvoiceNo,RepairCost) VALUES(?,?,?,?,?,?,?)";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql , new Object[] {truck.getTregNo(),truck.getVendorName(),truck.getPurchaseDate(),truck.getPrice(),truck.getRepairDate(),truck.getInvoiceNo(),truck.getRepairCost()});
}
Column TRegnNo can not be null. You have to assign a (unique) value to this row.
Check out with this :
StackTrace contains Column 'TRegnNo' cannot be null pointing to constraints in Truck table, like primary key or foreign key etc..

java.sq.SQLException: Column not found

I am receiving the following error:
HTTP Status 500 - Request processing failed; nested exception is
org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar
[SELECT id, name FROM track WHERE category_id = 1 ORDER BY name]; nested exception is
java.sql.SQLException: Column 'category_id' not found.
But when I copy and paste the very select statement listed in the error into a mysql shell, I get the result, which is expected as the table track has the column category_id.
What could be a reason for this error?
Here is the table create statement for track:
CREATE TABLE track (
id SERIAL
,name VARCHAR(50)
,category_id BIGINT UNSIGNED -- This references a serial (bigint unsigned)
,CONSTRAINT track_id_pk PRIMARY KEY (id)
,CONSTRAINT track_category_id_fk FOREIGN KEY
(category_id) REFERENCES category (id)
);
Here are some lines from my dao class regarding the track table:
private static final class TrackMapper implements RowMapper<Track> {
#Override
public Track mapRow(ResultSet resultSet, int rowNum) throws SQLException {
Track track = new Track();
track.setId(resultSet.getInt("id"));
track.setName(resultSet.getString("name"));
track.setCategoryId(resultSet.getInt("category_id"));
return track;
}
}
public List<Track> getTracks(int categoryId) {
String sql = "SELECT id, name FROM track WHERE category_id = " + categoryId + " ORDER BY name";
return jdbcTemplate.query(sql, new TrackMapper());
}
Check your SQL statement -- you need to include the category_id in the column list:
String sql = "SELECT id, name, category_id FROM track WHERE category_id = " + categoryId + " ORDER BY name";
It is failing because you're trying to extract category_id from the ResultSet and it isn't there.

Categories