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 - Spring和java中Environment对象初始化后如何调用方法?

java - 告诉 Hibernate 只为一个实体创建一个新表

java - Selenium 脚本启动层初始化期间显示错误

java - 将 servlet 重定向到另一个 html 页面

JAVA SQL - 找不到适用于 jdbc 的驱动程序 :derby

java - Spring MVC 尝试从 GET 请求方法中的重定向获取参数

java - 为什么@Transactional 不能与@Autowired EntityManagerFactory 一起工作?

java - 出现空指针异常。为什么?

spring - 域、DAO 和服务层

java - 带有 postgresql 的串行列上的 Spring Data JPA "null value in column xxx violates not-null constraint"