簡體   English   中英

使用Spring JDBC將數據插入到外表中

[英]Insert data into foreign table using Spring JDBC

我的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和stuff作為數據。 如何使用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);

另外,我如何維護交易?

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

任何幫助深表感謝!

看到這個簡單的例子,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&amp;password=root" />
</bean>

<bean class="Test" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM