AccessionListRepositoryCustomImpl.java

/**
 * Copyright 2015 Global Crop Diversity Trust
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/

package org.genesys.server.persistence;

import java.util.Collection;
import java.util.concurrent.atomic.AtomicInteger;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.genesys.server.model.genesys.AccessionList;
import org.genesys.server.service.filter.AccessionFilter;
import org.genesys.server.service.worker.AccessionProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class AccessionListRepositoryCustomImpl implements AccessionListCustomRepository {
    public static final Logger LOG = LoggerFactory.getLogger(AccessionListRepositoryCustomImpl.class);

	@PersistenceContext
	private EntityManager entityManager;

	@Autowired
	private AccessionProcessor accessionProcessor;

	@Override
	public int addAll(AccessionList accessionList, Collection<Long> accessionIds) {
		Query q = entityManager.createNativeQuery("insert ignore into accession_listitem (listid, acceid) values (?1, ?2)");
		q.setParameter(1, accessionList);
		int count = 0;
		for (Long acceId : accessionIds) {
			q.setParameter(2, acceId);
			count += q.executeUpdate();
		}
		return count;
	}

	@Override
	public int addAll(AccessionList accessionList, AccessionFilter filter) {
		Query q = entityManager.createNativeQuery("insert ignore into accession_listitem (listid, acceid) values (?1, ?2)");
		q.setParameter(1, accessionList);

		AtomicInteger count = new AtomicInteger(0);
		accessionProcessor.apply(filter, (accessions) -> {
			accessions.forEach((accession) -> {
				q.setParameter(2, accession.getId());
				count.addAndGet(q.executeUpdate());
			});
		});
		return count.get();
	}

	@Override
	public int removeAll(AccessionList accessionList) {
		Query q = entityManager.createNativeQuery("delete from accession_listitem where listid = ?1");
		q.setParameter(1, accessionList);
		return q.executeUpdate();
	}
}