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 vn.edu.vnuk.tasks_jpa.dao; import java.sql.Connection; import java.sql.SQLException; import java.util.Calendar; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.criteria.CriteriaQuery; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import vn.edu.vnuk.tasks_jpa.model.Task; /** * * @author michel */ @Repository public class TaskDao { private Connection connection; @Autowired public TaskDao(DataSource dataSource) throws SQLException { this.connection = dataSource.getConnection(); } public EntityManager getEntityManager() { EntityManagerFactory factory = Persistence.createEntityManagerFactory("vnuk-tasks-jpaPU"); return factory.createEntityManager(); } // CREATE public void create(Task task) throws SQLException { EntityManager manager = getEntityManager(); manager.getTransaction().begin(); manager.persist(task); manager.getTransaction().commit(); manager.close(); } // READ (List of Tasks) public List<Task> read() throws SQLException { EntityManager manager = getEntityManager(); CriteriaQuery criteria = manager.getCriteriaBuilder().createQuery(); criteria.select(criteria.from(Task.class)); return manager.createQuery(criteria).getResultList(); } // READ (Single Task) public Task read(Long id) throws SQLException { return getEntityManager().find(Task.class, id); } // UPDATE public void update(Task task) throws SQLException { EntityManager manager = getEntityManager(); manager.getTransaction().begin(); manager.merge(task); manager.getTransaction().commit(); manager.close(); } // DELETE public void delete(Long id) throws SQLException { Task task = this.read(id); EntityManager manager = getEntityManager(); manager.getTransaction().begin(); task = manager.merge(task); manager.remove(task); manager.getTransaction().commit(); manager.close(); } // OTHERS public void complete(Long id) throws SQLException { Task task = this.read(id); task.setAchieved(true); task.setDateOfAchievement(Calendar.getInstance()); this.update(task); } }