如果您使用的是 CRUD 存储库,那么 CRUD 存储库提供可用于单个实体(mongoCollection)的 save() 方法,或者您可以使用重载的 save 方法
<S extends T> List<S> saveAll(Iterable<S> entites)
它可以获取 Arraylist 并保存 Arraylist 对象。无需使用循环。
您可以看到下面的示例,其中 InventoryService 类创建了 3 个 Inventory 对象并将所有对象添加到 ArrayList 中,最后将其传递给作为 CRUD 存储库的清单存储库。
@Service
public class InventoryService {
private static final Logger LOGGER = LoggerFactory.getLogger(InventoryService.class);
@Autowired
private InventoryRepository inventoryRepository;
public void aveInventoryDetails() {
List<Inventory> inventoryList = new ArrayList<Inventory>();
inventoryList.add(new Inventory("500", 10));
inventoryList.add(new Inventory("600", 20));
inventoryList.add(new Inventory("700", 30));
try {
inventoryRepository.saveAll(inventoryList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
示例 Mongo 存储库
package com.bjs.repository;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.bjs.model.Inventory;
public interface InventoryRepository extends MongoRepository<Inventory, String> {
// empty as not defining any new method , we can use the existing save method
}
供参考 - http://docs.spring.io/autorepo/docs/spring-data-commons/1.9.1.RELEASE/api/org/springframework/data/repository/CrudRepository.html#save-java.lang.Iterable -