Reputation: 1591
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!
Upvotes: 3
Views: 5822
Reputation: 135992
See this simple example, all methods in class Test will be transactional, read Spring Framework docs for more
@Transactional
public class Test {
@Autowired
DataSource ds;
public void test1() throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
params.put("c1", "test");
SimpleJdbcInsert insert = new SimpleJdbcInsert(ds).withTableName("t1").usingColumns("c1")
.usingGeneratedKeyColumns("id");
long id = insert.executeAndReturnKey(params).longValue();
params = new HashMap<String, Object>();
params.put("stuff", "stuff");
params.put("id_fk", id);
SimpleJdbcInsert insert2 = new SimpleJdbcInsert(ds).withTableName(
"table2").usingColumns("stuff", "id_fk");
insert2.execute(params);
NamedParameterJdbcTemplate tmpl = new NamedParameterJdbcTemplate(ds);
params = new HashMap<String, Object>();
params.put("id", id);
String c1 = tmpl.queryForObject("select c1 from t1 where id = :id", params, String.class);
}
context
<context:annotation-config />
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?user=root&password=root" />
</bean>
<bean class="Test" />
Upvotes: 1