78 lines
2.4 KiB
Java
78 lines
2.4 KiB
Java
package envoy.server.database;
|
|
|
|
import java.util.List;
|
|
|
|
import javax.persistence.EntityManager;
|
|
import javax.persistence.Persistence;
|
|
|
|
import org.hibernate.Session;
|
|
|
|
import envoy.server.data.Message;
|
|
import envoy.server.data.User;
|
|
|
|
/**
|
|
* Project: <strong>envoy-server-standalone</strong><br>
|
|
* File: <strong>PersistenceManager.java</strong><br>
|
|
* Created: <strong>1 Jan 2020</strong><br>
|
|
*
|
|
* @author Leon Hofmeister
|
|
* @since Envoy Server Standalone v0.1-alpha
|
|
*/
|
|
public class PersistenceManager {
|
|
|
|
private EntityManager entityManager = Persistence.createEntityManagerFactory("envoy").createEntityManager();
|
|
|
|
/**
|
|
* Adds a {@link User} to the database.
|
|
*
|
|
* @param User the {@link User} to add to the database
|
|
* @since Envoy Server Standalone v0.1-alpha
|
|
*/
|
|
public void addUser(User User) { entityManager.persist(User); }
|
|
|
|
/**
|
|
* Adds a {@link Message} to the database.
|
|
*
|
|
* @param message the {@link Message} to add to the database
|
|
* @since Envoy Server Standalone v0.1-alpha
|
|
*/
|
|
public void addMessage(Message message) { entityManager.persist(message); }
|
|
|
|
/**
|
|
* Updates a {@link User} in the database
|
|
*
|
|
* @param user the {@link User} to add to the database
|
|
* @since Envoy Server Standalone v0.1-alpha
|
|
*/
|
|
public void updateUser(User user) { entityManager.unwrap(Session.class).merge(user); }
|
|
|
|
/**
|
|
* Updates a {@link Message} in the database.
|
|
*
|
|
* @param message the message to update
|
|
* @since Envoy Server Standalone v0.1-alpha
|
|
*/
|
|
public void updateMessage(Message message) { entityManager.unwrap(Session.class).merge(message); }
|
|
|
|
/**
|
|
* Searches for a user with a specific id.
|
|
*
|
|
* @param id - the id to search for
|
|
* @return the user with the specified id
|
|
* @since Envoy Server Standalone v0.1-alpha
|
|
*/
|
|
public User getUserById(long id) { return (User) entityManager.createNamedQuery("getUserById").setParameter("id", id).getSingleResult(); }
|
|
|
|
/**
|
|
* Returns all messages received while being offline.
|
|
*
|
|
* @param user - the user who wants to receive his unread messages
|
|
* @return all messages that the client does not yet have (unread messages)
|
|
* @since Envoy Server Standalone v0.1-alpha
|
|
*/
|
|
@SuppressWarnings("unchecked")
|
|
public List<Message> getUnreadMessages(User user) {
|
|
// TODO may need to be changed to clientId
|
|
return entityManager.createNamedQuery("getUnreadMessages").setParameter("recipient", user).getResultList();
|
|
}
|
|
} |