AccessionRepositoryCustomImpl.java

/*
 * Copyright 2019 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.gringlobal.persistence;

import org.gringlobal.model.Accession;
import org.gringlobal.model.QAccession;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;

public class AccessionRepositoryCustomImpl implements AccessionRepositoryCustom, InitializingBean {

	@Autowired
	private JPAQueryFactory jpaQueryFactory;

	@Override
	public void afterPropertiesSet() throws Exception {
	}

	@Override
	public long findMaxNumberPart2(final String numberPart1) {
		final JPAQuery<Long> x = jpaQueryFactory.from(QAccession.accession).select(QAccession.accession.accessionNumberPart2.max()).where(QAccession.accession.accessionNumberPart1
			.eq(numberPart1));

		Long max = x.fetchFirst();
		return max == null || max < 0 ? 0 : max;
	}

	@Override
	public Accession findOne(String name1, Long name2, String name3) {
		return jpaQueryFactory.selectFrom(QAccession.accession).where(
			// name1
			QAccession.accession.accessionNumberPart1.eq(name1)
				// name2
				.and(name2 == null ? QAccession.accession.accessionNumberPart2.isNull() : QAccession.accession.accessionNumberPart2.eq(name2))
				// name3
				.and(name3 == null ? QAccession.accession.accessionNumberPart3.isNull() : QAccession.accession.accessionNumberPart3.eq(name3)))
			// get
			.fetchOne();
	}

	@Override
	public void setAccessionNumber(Long accessionId, String accessionNumber) {
		jpaQueryFactory.update(QAccession.accession)
				.where(QAccession.accession.id.eq(accessionId))
				.set(QAccession.accession.accessionNumber, accessionNumber)
				.execute();
	}

}