uk.co.threeonefour.ifictionary.web.user.dao.JpaUserDao.java Source code

Java tutorial

Introduction

Here is the source code for uk.co.threeonefour.ifictionary.web.user.dao.JpaUserDao.java

Source

/**
 * Copyright 2014 Paul Illingworth
 * 
 * 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 uk.co.threeonefour.ifictionary.web.user.dao;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import uk.co.threeonefour.ifictionary.web.user.model.User;

public class JpaUserDao implements UserDao {

    @PersistenceContext
    private EntityManager entityManager;

    public JpaUserDao() {
    }

    @Transactional
    public User get(String id) {

        EntityManager em = entityManager;
        return em.find(User.class, id);
    }

    @Transactional
    @Override
    public User add(User user) {

        EntityManager em = entityManager;
        em.persist(user);
        em.flush();
        return user;
    }

    @Transactional
    @Override
    public User update(User user) {

        EntityManager em = entityManager;
        em.merge(user);
        em.flush();
        return user;
    }

    @Transactional
    @Override
    public void remove(String id) {

        EntityManager em = entityManager;
        em.remove(get(id));
        em.flush();
    }

    @Transactional
    @Override
    public User findUser(String userId) {
        String query = "SELECT u FROM User AS u WHERE userId=:userId";
        EntityManager em = entityManager;
        Query q = em.createQuery(query.toString());
        q.setParameter("userId", userId);
        try {
            return (User) q.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

}