我有 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/