com.epam.ipodromproject.repository.jpa.JPAHorseRepository.java Source code

Java tutorial

Introduction

Here is the source code for com.epam.ipodromproject.repository.jpa.JPAHorseRepository.java

Source

/*
 * 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.Horse;
import com.epam.ipodromproject.repository.HorseRepository;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Oleh
 */
@Repository("horseRepository")
public class JPAHorseRepository implements HorseRepository {

    @PersistenceContext
    EntityManager entityManager;

    public JPAHorseRepository() {
    }

    @Override
    public Horse getHorseById(Long id) {
        return entityManager.find(Horse.class, id);
    }

    @Override
    public Long save(Horse horse) {
        entityManager.persist(horse);
        return horse.getId();
    }

    @Override
    public Long update(Horse horse) {
        entityManager.merge(horse);
        return horse.getId();
    }

    @Override
    public boolean delete(Horse horse) {
        entityManager.remove(horse);
        return true;
    }

    @Override
    public Horse getHorseByName(String name) {
        TypedQuery query = entityManager.createNamedQuery("Horse.findByName", Horse.class);
        query.setParameter("name", name);
        Horse horse = null;
        try {
            horse = (Horse) query.getSingleResult();
        } catch (Exception e) {

        }
        return horse;
    }

    @Override
    public long getPagesOfHorses(String partOfName) {
        TypedQuery<Long> query = entityManager.createNamedQuery("Horse.findNumberOfHorsesByPartOfName", Long.class);
        StringBuilder partOfNameBuilder = new StringBuilder("%");
        query.setParameter("partOfName", partOfNameBuilder.append(partOfName).append("%").toString());
        long pages = 1;
        try {
            pages = query.getSingleResult();
        } catch (Exception e) {
            pages = (long) 1;
        }
        return pages;
    }

    @Override
    public List<Horse> getHorsesByPageAndPartOfName(String partOfName, int startingResult, int resultsCount) {
        TypedQuery<Horse> query = entityManager.createNamedQuery("Horse.getHorsesByPageAndPartOfName", Horse.class);
        StringBuilder partOfNameBuilder = new StringBuilder("%");
        query.setParameter("partOfName", partOfNameBuilder.append(partOfName).append("%").toString());
        return query.setMaxResults(resultsCount).setFirstResult(startingResult).getResultList();
    }

}