Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.epam.ipodromproject.repository.jpa; import com.epam.ipodromproject.domain.Competition; import com.epam.ipodromproject.domain.CompetitionState; import com.epam.ipodromproject.repository.CompetitionRepository; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.hibernate.Hibernate; import org.springframework.stereotype.Repository; /** * * @author Oleh */ @Repository("competitionRepository") public class JPACompetitionRepository implements CompetitionRepository { @PersistenceContext EntityManager entityManager; public JPACompetitionRepository() { } public JPACompetitionRepository(EntityManager entityManager) { this.entityManager = entityManager; } @Override public Competition getCompetitionById(Long id) { Competition competition = entityManager.find(Competition.class, id); Hibernate.initialize(competition.getHorses()); return competition; } @Override public Long save(Competition competition) { entityManager.persist(competition); return competition.getId(); } @Override public Long update(Competition competition) { entityManager.merge(competition); return competition.getId(); } @Override public boolean delete(Competition competition) { entityManager.remove(competition); return true; } @Override public List<Competition> getAllCompetitionsAfter(Date date, int startingResult, int resultsCount) { TypedQuery<Competition> query = entityManager.createNamedQuery("Competition.findAfterDate", Competition.class); query.setParameter("date", date); query.setParameter("state", CompetitionState.NOT_REGISTERED); List<Competition> resultList = query.setMaxResults(resultsCount).setFirstResult(startingResult) .getResultList(); for (Competition competition : resultList) { Hibernate.initialize(competition.getHorses()); } return resultList; } @Override public List<Competition> getUnoperatedCompetitions(int startingResult, int resultsCount) { TypedQuery<Competition> query = entityManager.createNamedQuery("Competition.findUnoperated", Competition.class); query.setParameter("state", CompetitionState.NOT_REGISTERED); query.setParameter("date", new Date()); List<Competition> resultList = query.setMaxResults(resultsCount).setFirstResult(startingResult) .getResultList(); for (Competition competition : resultList) { Hibernate.initialize(competition.getHorses()); } return resultList; } }