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 cz.muni.fi.dndtroops.dao; import cz.muni.fi.dndtroops.entity.User; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; /** * * @author Karel Auf */ @Repository public class UserDaoImpl implements UserDao { final static Logger log = LoggerFactory.getLogger(UserDaoImpl.class); @PersistenceContext private EntityManager em; @Override public void create(User u) { log.debug("create({})", u); validate(u); if (u.getId() != null) { throw new IllegalArgumentException("user id is already set"); } em.persist(u); } @Override public User findById(Long id) { log.debug("findById({})", id); if (id == null) { throw new IllegalArgumentException("id is null"); } return em.find(User.class, id); } @Override public User findByName(String name) { log.debug("findByName({})", name); if (name == null) { throw new IllegalArgumentException("name is null"); } if (name.length() == 0) { throw new IllegalArgumentException("name is empty string"); } try { TypedQuery<User> query = em.createQuery("SELECT u FROM User u WHERE u.name = :name", User.class); return query.setParameter("name", name).getSingleResult(); } catch (NoResultException nre) { return null; } } @Override public List<User> findAll() { log.debug("findAll({})"); return em.createQuery("select u from User u", User.class).getResultList(); } @Override public void delete(User u) { log.debug("delete({})", u); if (u == null) { throw new IllegalArgumentException("user pointer is null"); } em.remove(u); } private static void validate(User u) { if (u == null) { throw new IllegalArgumentException("user pointer is null"); } if (u.getName() == null) { throw new IllegalArgumentException("user name is null"); } if (u.getPasswdHash() == null) { throw new IllegalArgumentException("user password is null"); } } }