2013-01-05 41 views
2

我在我的MySQL數據庫的兩個表:將數據插入外部表使用Spring JDBC

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) 
) 

我想在這兩個表中插入一條記錄。基本上,我有編號,名稱&東西作爲數據。如何使用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); 

雖然插入表2,我如何獲得價值從表1的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); 

另外,如何維護交易?

另外,如何獲取給定名稱的數據?

任何幫助非常感謝!

回答

1

看到這個簡單的例子,在課堂測試的所有方法將是事務性的,閱讀Spring框架文檔的更多

@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&amp;password=root" /> 
</bean> 

<bean class="Test" /> 
+0

感謝示例代碼。我可以看到你插入到表t1中,但是使用從表t1生成的id插入到表t2中呢? –

+0

請參閱我的更新與insert2 –

+0

謝謝...還有一個問題:我需要添加transactionManager bean與數據源屬性?誰將調用transactionManager? –

相關問題