简体   繁体   中英

Save method of org.hibernate.Session is not saving data in database

I have Spring Boot application in which I am reading CSV file and trying to save it in database.

Below is the main boot class.

@SpringBootApplication
@ComponentScan("com.abg.meter")
@PropertySource(ignoreResourceNotFound = false, value = "file:${user.home}/application.properties")
@EnableTransactionManagement
public class ABGExecution{

public static void main(String[] args) {
    SpringApplication.run(ABGExecution.class, args);
 }
}

Below is the CustomIdGenerator

public class CustomIdGenerator implements IdentifierGenerator {

@Override
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
    long i = 0;
    Connection connection = null;
    Statement statement = null;
    ResultSet resultSet = null;
    try {
        connection = session.connection();
        statement = connection.createStatement();
        resultSet = statement.executeQuery("SELECT max(id) FROM public.sku_details");
        if (resultSet.next()) {
            i = resultSet.getLong(1);
            i = i + 1;
        }
    } catch (Exception e) {
        throw new HibernateException("Unable to generate Indetifier " + e.getMessage());
    }
    System.out.println("generated id is "+i);
    return i;
}
}

Below is my service method

@Transactional
public void saveCSVData(){
   for(int i=0; i<=rowCount; i==){
      skudao.save(skudetails);
   }
}

Whenever save method is called CustomIdGenerator is generating and id. For example it generated 5 as id. Once save method is called it does not persist entity immediately. Entity remain attached with session. That is why for next save CustomIdGenerator generates 5 as id again. So when I call save method again I am getting below exception.

org.springframework.dao.DuplicateKeyException: A different object with the same identifier value was already associated with the session : [com.abg.meter.pojo.SkuDetails#5]; nested exception is org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [com.abg.meter.pojo.SkuDetails#5]

You should call flush() on the session or entity manager to execute the insert statement.

Or you could run every save in its own transaction.

Otherwise the database will not be changed.

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