package com.example.beer.dao;

import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.example.beer.model.Project;

@Singleton
public class ProjectDAO {
	
	@PersistenceContext
	private EntityManager em;
	
	public boolean addProject(Project project) {
		Project foundProject = findProjectByName(project.getName());
		
		if (foundProject != null) {
			em.persist(project);
			return true;
		} else {
			// TODO: Maybe update project title or users, or tasks?
			return false;
		}
	}

	public Project findProjectByName(String name) {
		String idQueryText = "SELECT p FROM Project p WHERE p.name= :projectName";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectName", name);
		
		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public Project findProjectById(int projectId) {
		String idQueryText = "SELECT p FROM Project p WHERE p.id= :projectId";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectId", projectId);
		
		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
}

package com.example.beer.dao;

import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.example.beer.model.Project;

@Singleton
public class ProjectDAO {
	
	@PersistenceContext
	private EntityManager em;
	
	public boolean addProject(Project project) {
		Project foundProject = findProjectByName(project.getName());
		
		if (foundProject == null) {
			em.persist(project);
			return true;
		} else {
			// TODO: Maybe update project title or users, or tasks?
			return false;
		}
	}

	public Project findProjectByName(String name) {
		String idQueryText = "SELECT p FROM Project p WHERE p.name= :projectName";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectName", name);
		
		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
	
	public Project findProjectById(int projectId) {
		String idQueryText = "SELECT p FROM Project p WHERE p.id= :projectId";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectId", projectId);
		
		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
}

Fix a logical error. A new project was persisted if it was already found found in the database. It should be the opposite
Fix a logical error. A new project was persisted if it
was already found found in the database. It should be the opposite
