java - org.hibernate.Session 的 Save 方法未将数据保存在数据库中

标签 java spring hibernate spring-boot

我有 Spring Boot 应用程序,我正在其中读取 CSV 文件并尝试将其保存在数据库中。

下面是主引导类。

@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);
 }
}

下面是 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;
}
}

以下是我的服务方法

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

每当调用 Save 方法时 CustomIdGenerator 就会生成 id。例如它生成 5 作为 id。一旦调用 save 方法,它不会立即保留实体。实体与 session 保持连接。这就是为什么下一次保存时 CustomIdGenerator 会再次生成 5 作为 id。因此,当我再次调用 save 方法时,我遇到了异常。

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]

最佳答案

您应该在 session 或实体管理器上调用flush()来执行插入语句。

或者您可以在自己的事务中运行每个保存。

否则数据库将不会更改。

关于java - org.hibernate.Session 的 Save 方法未将数据保存在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214682/

相关文章:

java - org.springframework.beans.factory.NoSuchBeanDefinitionException : No bean named 'BookDao' is defined

java - 使用 Spring Jdbc 模板面对嵌套 beans 查询

java - 如何@autowire 一些 bean 进入 JsonSerializer?

java - org.hibernate.PropertyAccessException : exception setting property value with CGLIB

java - 我可以查询 Spring JPA @Query 来查找列表与另一个列表的任何匹配项吗?

java - Hibernate 3.2.5 与 Play Framework 1.2.5

java - 在链表后面插入和删除节点的方法

java - 迭代 List<> 中包含的 HashMap<> 以获取包含在映射中的数组变量作为 java 中的值

java - Spring Tool Suite 和 Spring Configurator - 目录结构

Java 动态绑定(bind)与静态绑定(bind)