CodeValueLangRepositoryCustomImpl.java

/*
 * Copyright 2020 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 static org.gringlobal.service.LanguageService.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.gringlobal.model.CodeValue;
import org.gringlobal.model.QCodeValue;
import org.gringlobal.model.QCodeValueLang;
import org.gringlobal.model.QSysLang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;

import com.querydsl.jpa.impl.JPAQueryFactory;

/**
 * @author Maxym Borodenko
 */
public class CodeValueLangRepositoryCustomImpl implements CodeValueLangRepositoryCustom {

	@Autowired
	private JPAQueryFactory jpaQueryFactory;

	@Override
	@Cacheable(value = "codevaluetitles", key = "'codevalue-' + #groupName + '-' + #value")
	public Set<String> findAllTitles(String groupName, String value) {
		QCodeValue cv = new QCodeValue("cv");

		List<String> titles = jpaQueryFactory.from(QCodeValueLang.codeValueLang).select(QCodeValueLang.codeValueLang.title)
				.innerJoin(QCodeValueLang.codeValueLang.entity(), cv).on(cv.id.eq(QCodeValueLang.codeValueLang.entity().id))
				.where(cv.groupName.eq(groupName).and(cv.value.eq(value)))
				.fetch();

		return new HashSet<>(titles);
	}

	@Override
	public CodeValue findCodeValueOfMCPD(String groupName, String mcpd) {
		QCodeValue cv = new QCodeValue("cv");
		QSysLang sl = new QSysLang("sl");

		List<CodeValue> codeValues = jpaQueryFactory.from(QCodeValueLang.codeValueLang).select(QCodeValueLang.codeValueLang.entity())
				.innerJoin(QCodeValueLang.codeValueLang.entity(), cv)
				.innerJoin(QCodeValueLang.codeValueLang.sysLang(), sl)
				.where(cv.groupName.eq(groupName).and(QCodeValueLang.codeValueLang.title.eq(mcpd)).and(QCodeValueLang.codeValueLang.sysLang().ietfTag.eq(MCPD_IETF_TAG)))
				.fetch();

		// there could be multiple CVs with the same MCPD value we only take the first one
		return codeValues.size() > 0 ? codeValues.get(0) : null;
	}

}