我的MySQL数据库中有两个表:
CREATE TABLE table1 (
id int auto_increment,
name varchar(10),
CONSTRAINT pk_id primary key(id)
)
和
CREATE TABLE table2 (
id_fk int,
stuff varchar(30),
CONSTRAINT fk_id FOREIGN KEY(id_fk) REFERENCES table1(id)
)
我想在这两个表中插入一条记录。基本上,我是id,name&东西作为数据。如何使用Spring JDBC将它们插入到两个表中?
我正在插入表格,如下所示:
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);
插入table2时,如何从table1获取id值?
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);
另外,我如何维护交易?
另外,我如何获取给定名称的数据?
非常感谢任何帮助!
答案 0 :(得分:1)
看到这个简单的例子,Test类中的所有方法都是事务性的,阅读更多的Spring Framework文档
@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: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" />