I have two tables in my MySQL database:
CREATE TABLE table1 (
id int auto_increment,
name varchar(10),
CONSTRAINT pk_id primary key(id)
)
and
CREATE TABLE table2 (
id_fk int,
stuff varchar(30),
CONSTRAINT fk_id FOREIGN KEY(id_fk) REFERENCES table1(id)
)
I want to insert a record in both of these tables. Basically, I’ve id, name & stuff as data. How do I insert them into both tables using Spring JDBC?
I’m inserting into tables as shown below:
SimpleJdbcInsert insert1 = new SimpleJdbcInsert(this.getDataSource())
.withTableName("table1")
.usingColumns("name");
Map<String, Object> parameters1 = new HashMap<String, Object>();
parameters1.put("name", myObj1.getStuff());
insert.execute(parameters1);
While inserting into table2, how do I get the id value from table1?
SimpleJdbcInsert insert2 = new SimpleJdbcInsert(this.getDataSource())
.withTableName("table2")
.usingColumns("stuff");
Map<String, Object> parameters2 = new HashMap<String, Object>();
parameters2.put("stuff", myObj2.getStuff());
insert.execute(parameters2);
Also, how do I maintain transaction?
Also, how do I fetch data for a given name?
Any help is much appreciated!
See this simple example, all methods in class Test will be transactional, read Spring Framework docs for more
context