简体   繁体   中英

Get id after insert in Spring

I try to retrive id after insert in Spring but this solution not work:

String sqlquery2 = "INSERT into tab (attr1,attr2) VALUES (?,?)";
String sql1 ="select last_insert_id()";

jdbcTemplateObject.update(sqlquery2, value1, value2);
int id = jdbcTemplateObject.update(sql1);

For each jdbc access, Spring use a connection for it's connection pool.

So it may use one connection from its pool, to make the insert, and another connection for the last_insert_id query.

The problem is that the last_insert_id query is tied to the connection that actually made the insert.

In order to force Spring JdbcTemplate to use the same connection all along a portion of code is to start a Transaction before the insert, and commit it after the last_insert_id query.

use @Transactional

Reference

To better explain the example cited by Xstian, there are some instructions now deprecated. you need to do this:

in Beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:ldap="http://www.springframework.org/schema/ldap"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/ldap 
        http://www.springframework.org/schema/ldap/spring-ldap.xsd">


    <context:property-placeholder location="/config/application.properties" />



    <!-- Initialization for data source JDBC -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- Definition for studentJDBCTemplate bean -->
    <bean id="studentJDBCTemplate" class="com.balduzzi.database.StudentJDBCTemplate">
        <property name="dataSource" ref="dataSource" />
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>

    <!-- Initialization for TransactionManager -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
  ...

and in Java method:

public void insertStudent1(String name, String lastname, String password,String hashpass,String studentype,String codfac) {

          TransactionDefinition def = new DefaultTransactionDefinition();
          TransactionStatus status = transactionManager.getTransaction(def);

        try {
        String sqlinsertab1l = "INSERT into tab1 (type, cod)"
                          +"VALUES (?, ?)";

        jdbcTemplateObject.update(sqlinsertabl, studentype, codfac);


        String sqlgetlastidtab1 = "select max(id) from tab1";

        tab1last_id = jdbcTemplateObject.queryForObject(sqlgetlastidtab1,Integer.class);

        String sqlinsertab2 = "INSERT into tab2 (password,hashpassword) VALUES (?,?)";

        jdbcTemplateObject.update(sqlinsertab2, password, hashpass);

        String sqlgetlastidtab2 = "select max(id) from tab2";

        tab2last_id = jdbcTemplateObject.queryForObject(sqlgetlastidtab2,Integer.class );

        String sqlinsertstud = "INSERT into tab3 (tab1_id,tab2_id,name,lastname) " + "VALUES (?, ?, ?, ?)";

        jdbcTemplateObject.update(sqlinsertstud, tab1last_id, tab2last_id, name, lastname);


        transactionManager.commit(status);
         }
          catch (DataAccessException e) {
              System.out.println("Error in creating record, rolling back");
              transactionManager.rollback(status);
              throw e;
         }
          return;      
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM