<commit_before>/*
 *  Copyright 2012 JAXIO http://www.jaxio.com
 *
 * 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.querybyexample.jpa;

import static org.querybyexample.jpa.JpaUtil.buildJpaOrders;
import static org.querybyexample.jpa.ByEntitySelectorUtil.byEntitySelectors;
import static org.querybyexample.jpa.ByPropertySelectorUtil.byPropertySelectors;
import static org.querybyexample.jpa.ByRangeUtil.byRanges;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;

/**
 * JPA 2 Generic DAO with find by example/range/pattern and CRUD support.
 */
public abstract class QueryByExample<E extends Identifiable<PK>, PK extends Serializable> {

	@Inject
	private ByExampleUtil byExampleUtil;
	@Inject
	private ByPatternUtil byPatternUtil;
	@Inject
	private NamedQueryUtil namedQueryUtil;
	@PersistenceContext
	private EntityManager entityManager;

	private Class<E> type;
	private Logger log;
	private String cacheRegion;

	protected EntityManager getEntityManager() {
		return entityManager;
	}

	protected ByExampleUtil getByExampleUtil() {
		return byExampleUtil;
	}

	protected ByPatternUtil getByPatternUtil() {
		return byPatternUtil;
	}

	protected NamedQueryUtil getNamedQueryUtil() {
		return namedQueryUtil;
	}

	/**
	 * This constructor needs the real type of the generic type E so it can be passed to the {@link EntityManager}.
	 */
	public QueryByExample(Class<E> type) {
		this.type = type;
		this.log = Logger.getLogger(getClass());
		this.cacheRegion = type.getCanonicalName();
	}

	/**
	 * Gets from the repository the E entity instance.
	 * 
	 * DAO for the local database will typically use the primary key or unique fields of the passed entity, while DAO for external repository may use a unique
	 * field present in the entity as they probably have no knowledge of the primary key. Hence, passing the entity as an argument instead of the primary key
	 * allows you to switch the DAO more easily.
	 * 
	 * @param entity an E instance having a primary key set
	 * @return the corresponding E persistent instance or null if none could be found.
	 */
	public E get(E entity) {
		if (entity == null) {
			return null;
		}

		Serializable id = entity.getId();
		if (id == null) {
			return null;
		}

		E entityFound = getEntityManager().find(type, id);

		if (entityFound == null) {
			log.warn("get returned null with pk=" + id);
		}

		return entityFound;
	}

	/**
	 * Find and load a list of E instance.
	 * 
	 * @param entity a sample entity whose non-null properties may be used as search hints
	 * @return the entities matching the search.
	 */
	public List<E> find(E entity) {
		return find(entity, new SearchParameters());
	}

	/**
	 * Find and load a list of E instance.
	 * 
	 * @param entity a sample entity whose non-null properties may be used as search hints
	 * @param searchParameters carries additional search information
	 * @return the entities matching the search.
	 */
	@SuppressWarnings("unchecked")
	public List<E> find(E entity, SearchParameters sp) {
		if (sp.hasNamedQuery()) {
			return getNamedQueryUtil().findByNamedQuery(sp);
		}
		CriteriaBuilder builder = entityManager.getCriteriaBuilder();
		CriteriaQuery<E> criteriaQuery = builder.createQuery(type);
		Root<E> root = criteriaQuery.from(type);

		// predicate
		Predicate predicate = getPredicate(root, criteriaQuery, builder, entity, sp);
		if (predicate != null) {
			criteriaQuery = criteriaQuery.where(predicate);
		}

		// left join
		if (sp.hasLeftJoinAttributes()) {
			for (SingularAttribute<?, ?> arg : sp.getLeftJoinAttributes()) {
				root.fetch((SingularAttribute<E, ?>) arg, JoinType.LEFT);
			}
		}

		// order by
		criteriaQuery.orderBy(buildJpaOrders(sp.getOrders(), root, builder));

		TypedQuery<E> typedQuery = entityManager.createQuery(criteriaQuery);

		// cache
		setCacheHints(typedQuery, sp);

		// pagination
		if (sp.getFirstResult() >= 0) {
			typedQuery.setFirstResult(sp.getFirstResult());
		}
		if (sp.getMaxResults() > 0) {
			typedQuery.setMaxResults(sp.getMaxResults());
		}
<commit_msg>fix many to many<commit_after>/*
 *  Copyright 2012 JAXIO http://www.jaxio.com
 *
 * 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.querybyexample.jpa;

import static org.querybyexample.jpa.JpaUtil.buildJpaOrders;
import static org.querybyexample.jpa.ByEntitySelectorUtil.byEntitySelectors;
import static org.querybyexample.jpa.ByPropertySelectorUtil.byPropertySelectors;
import static org.querybyexample.jpa.ByRangeUtil.byRanges;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;

import org.apache.commons.lang.Validate;
import org.apache.log4j.Logger;

/**
 * JPA 2 Generic DAO with find by example/range/pattern and CRUD support.
 */
public abstract class QueryByExample<E extends Identifiable<PK>, PK extends Serializable> {

	@Inject
	private ByExampleUtil byExampleUtil;
	@Inject
	private ByPatternUtil byPatternUtil;
	@Inject
	private NamedQueryUtil namedQueryUtil;
	@PersistenceContext
	private EntityManager entityManager;

	private Class<E> type;
	private Logger log;
	private String cacheRegion;

	protected EntityManager getEntityManager() {
		return entityManager;
	}

	protected ByExampleUtil getByExampleUtil() {
		return byExampleUtil;
	}

	protected ByPatternUtil getByPatternUtil() {
		return byPatternUtil;
	}

	protected NamedQueryUtil getNamedQueryUtil() {
		return namedQueryUtil;
	}

	/**
	 * This constructor needs the real type of the generic type E so it can be passed to the {@link EntityManager}.
	 */
	public QueryByExample(Class<E> type) {
		this.type = type;
		this.log = Logger.getLogger(getClass());
		this.cacheRegion = type.getCanonicalName();
	}

	/**
	 * Gets from the repository the E entity instance.
	 * 
	 * DAO for the local database will typically use the primary key or unique fields of the passed entity, while DAO for external repository may use a unique
	 * field present in the entity as they probably have no knowledge of the primary key. Hence, passing the entity as an argument instead of the primary key
	 * allows you to switch the DAO more easily.
	 * 
	 * @param entity an E instance having a primary key set
	 * @return the corresponding E persistent instance or null if none could be found.
	 */
	public E get(E entity) {
		if (entity == null) {
			return null;
		}

		Serializable id = entity.getId();
		if (id == null) {
			return null;
		}

		E entityFound = getEntityManager().find(type, id);

		if (entityFound == null) {
			log.warn("get returned null with pk=" + id);
		}

		return entityFound;
	}

	/**
	 * Find and load a list of E instance.
	 * 
	 * @param entity a sample entity whose non-null properties may be used as search hints
	 * @return the entities matching the search.
	 */
	public List<E> find(E entity) {
		return find(entity, new SearchParameters());
	}

	/**
	 * Find and load a list of E instance.
	 * 
	 * @param entity a sample entity whose non-null properties may be used as search hints
	 * @param searchParameters carries additional search information
	 * @return the entities matching the search.
	 */
	@SuppressWarnings("unchecked")
	public List<E> find(E entity, SearchParameters sp) {
		if (sp.hasNamedQuery()) {
			return getNamedQueryUtil().findByNamedQuery(sp);
		}
		CriteriaBuilder builder = entityManager.getCriteriaBuilder();
		CriteriaQuery<E> criteriaQuery = builder.createQuery(type).distinct(true);
		Root<E> root = criteriaQuery.from(type);

		// predicate
		Predicate predicate = getPredicate(root, criteriaQuery, builder, entity, sp);
		if (predicate != null) {
			criteriaQuery = criteriaQuery.where(predicate);
		}

		// left join
		if (sp.hasLeftJoinAttributes()) {
			for (SingularAttribute<?, ?> arg : sp.getLeftJoinAttributes()) {
				root.fetch((SingularAttribute<E, ?>) arg, JoinType.LEFT);
			}
		}

		// order by
		criteriaQuery.orderBy(buildJpaOrders(sp.getOrders(), root, builder));

		TypedQuery<E> typedQuery = entityManager.createQuery(criteriaQuery);

		// cache
		setCacheHints(typedQuery, sp);

		// pagination
		if (sp.getFirstResult() >= 0) {
			typedQuery.setFirstResult(sp.getFirstResult());
		}
		if (sp.getMaxResults() > 0) {
			typedQuery.setMaxResults(sp.getMaxResults());
		}

{'fraction_non_alphanumeric': 0.0926464881645324, 'fraction_numerical': 0.002328288707799767, 'mean_word_length': 4.372068785825951, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3136280', 'n_tokens_mistral': 3133, 'n_tokens_neox': 2938, 'n_words': 967}