Java tutorial
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 com.siriusit.spezg.multilib.storage.jpa; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.springframework.stereotype.Repository; import com.siriusit.spezg.multilib.domain.Message; import com.siriusit.spezg.multilib.domain.Person; import com.siriusit.spezg.multilib.domain.jpa.MessageDomainObject; import com.siriusit.spezg.multilib.storage.MessageRepository; /** * * @author Tommy B <Tommy.Bo@SiriusIT.com> */ @Repository("messageRepository") public class JpaMessageRepository implements MessageRepository { @PersistenceContext(unitName = "multilib-db") private EntityManager entityManager; public EntityManager getEntityManager() { return entityManager; } public void setEntityManager(EntityManager entityManager) { this.entityManager = entityManager; } @Override public Message createMessage(Person receiver, String sender, String subject, String message) { Message messageObject = new MessageDomainObject(receiver, sender, new Date(), false, subject, message); entityManager.persist(messageObject); return messageObject; } @Override public void updateMessage(Message message) { if (!entityManager.contains(message)) entityManager.merge(message); else entityManager.persist(message); } @Override public void deleteMessage(Message message) { entityManager.remove(message); } @Override public List<? extends Message> findMessagesByReceiver(Person receiver) { TypedQuery<MessageDomainObject> query = entityManager.createNamedQuery("findMessageByReceiver", MessageDomainObject.class); query.setParameter("receiver", receiver); return query.getResultList(); } @Override public Message findMessageById(Long id) { return entityManager.find(MessageDomainObject.class, id); } @Override public long countMessagesByViewedState(Person receiver, boolean viewedState) { TypedQuery<Long> query = entityManager.createNamedQuery("findMessageByViewedState", Long.class); query.setParameter("receiver", receiver); query.setParameter("viewed", viewedState); return query.getSingleResult(); } }