com.tamnd2.basicwebapp.core.repositories.jpa.JpaBlogRepo.java Source code

Java tutorial

Introduction

Here is the source code for com.tamnd2.basicwebapp.core.repositories.jpa.JpaBlogRepo.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.tamnd2.basicwebapp.core.repositories.jpa;

import com.tamnd2.basicwebapp.core.entities.Blog;
import com.tamnd2.basicwebapp.core.repositories.BlogRepo;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author tamnd2
 */
@Repository
public class JpaBlogRepo implements BlogRepo {

    @PersistenceContext
    private EntityManager em;

    @Override
    public Blog createBlog(Blog data) {
        em.persist(data);
        return data;
    }

    @Override
    public List<Blog> findAllBlogs() {
        Query query = em.createQuery("SELECT b from Blog b");
        return query.getResultList();
    }

    @Override
    public Blog findBlog(Long id) {
        return em.find(Blog.class, id);
    }

    @Override
    public Blog findBlogByTitle(String title) {
        Query query = em.createQuery("SELECT b from Blog b where b.title=?1");
        query.setParameter(1, title);
        List<Blog> blogs = query.getResultList();
        if (blogs.isEmpty()) {
            return null;
        } else {
            return blogs.get(0);
        }
    }

    @Override
    public List<Blog> findBlogsByAccount(Long accountId) {
        Query query = em.createQuery("SELECT b from Blog b where b.owner.id=?1");
        query.setParameter(1, accountId);
        return query.getResultList();
    }
}