Creazione di una semplice web application utilizzando maven, jpa2, spring, struts2, mysql (parte 3)

Ora possiamo iniziare a costruire la nostra applicazione.

Per prima cosa implementiamo il modello. Il nostro dominio in questo caso è l’utente e sarà rappresentato dalla classe User.java. Questa classe rappresenterà il nostro utente nel sistema. Verranno quindi implementati i metodi setter/getter che modificheranno le proprietà id, username, password

User.java

package it.sample.webapp.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Defines a model that represents a user in the system.
 */

@Entity
@Table(name = "user")
public class User implements Serializable {
  private static final long serialVersionUID = -2230673925164485629L;
  
  @Id
  @GeneratedValue
  private Long id;
  
  private String username;
  private String password;

  
  

  /**
   * Sets the unique id for this user
   * @param id unique id to be assigned
   */
  public void setId(Long id) {
    this.id = id;
  }
  
  /**
   * Gets the unique id assigned to this user
   * @return the unique id
   */
  public Long getId() {
    return id;
  }
  
  /**
   * Gets the name of this user
   * @return the name
   */
  public final String getUsername() {
    return username;
  }
  
  /**
   * Sets the name of this user. 
   * @param name the name to set
   */
  public final void setUsername(String username) {
    this.username = username;
  }
  
  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }


}

									

A questo punto possiamo implementare gli oggetti DAO per l’accesso al DB.

Per fare questo implementiamo prima un’interfaccia generica che espone i metodi principali di accesso al DB (delete, getAll, getById,save) e poi una classe astratta che esegue un’implementazione di default della classe GenericDao. Ci preoccuperemo di implementare l’interfaccia in un secondo momento.

GenericDao.java

package it.sample.webapp.dao;

import java.io.Serializable;
import java.util.List;

/**
 * Defines a generic data access object that is extended by all the DAOs in the
 * system. This interface defines the common CRUD methods like <code>save</code>, 
 * <code>delete</code> <code>getAll</code> and <code>getById</code>.
 */
public interface GenericDao <T, ID extends Serializable> {
  
  /**
   * Gets the list of all objects of this type  
   * @return list of this objects; the list can be empty
   */
  public List<T>  getAll();
  
  /**
   * Gets the object using specified primary key
   * @param id primary key (ID) of the object to retrieve
   * @return object corresponding to the specified primary key (ID)
   * @throws javax.persistence.NoResultException when object
   *     corresponding to the specified ID (primary key) is not found. This is a
   *     <code>RuntimeException</code>
   */
  public T getById(ID id);
  
  /**
   * Saves the specified object. Handles both insert as well as update
   * @param object the object to save
   * @return managed copy of the original object. Use this object if you want 
   *       the future changes managed (persisted).
   * @throws javax.persistence.PersistenceException when the specified object
   *     could not be persisted. This is a
   *     <code>RuntimeException</code>
   */
  public T save(T  object);
  
  /**
   * Deletes the object that corresponds to the specified primary key (ID)
   * @param object the object to delete
   * @throws javax.persistence.PersistenceException when the specified object
   *     could not be deleted. This is a
   *     <code>RuntimeException</code>
   */
  public void delete(ID  id);
}

									

BaseJpaDao.java

package it.sample.webapp.dao.jpa;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import it.sample.webapp.dao.GenericDao;

/**
 * Defines a Base DAO that provides JPA implementation. 
 * This class keeps the reference to the <code>EntityManager</code> and 
 * provides a default implementation for methods defined in the <code>GenericDao</code>
 * interface.
 */
public abstract class BaseJpaDao<T, ID extends Serializable> implements GenericDao<T, ID> {
  private Class<T> persistentClass;
  protected EntityManager entityManager;

  /**
     * Constructor that takes in a class to see which type of entity to persist
     * @param persistentClass the class type you'd like to persist
     */
    public BaseJpaDao(final Class<T> persistentClass) {
        this.persistentClass = persistentClass;
    }
  
  /**
   * Gets the <code>EntityManager</code> used by this DAO
   * @return the entityManager used for persistence
   */
  public final EntityManager getEntityManager() {
    return entityManager;
  }

  /**
   * Sets the <code>EntityManager</code> used by this DAO
   * @param entityManager the entityManager to be used for persistence
   */
  @PersistenceContext
  public final void setEntityManager(EntityManager entityManager) {
    this.entityManager = entityManager;
  }
  
  @Override
  public void delete(ID id) {
    this.entityManager.remove(id);
    
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<T> getAll() {
    Query q = this.entityManager.createQuery("FROM " + 
                         this.persistentClass.getName());
    return q.getResultList();
  }

  @Override
  public T getById(ID id) {
    final T data= this.entityManager.find(persistentClass, id);
    return data;
  }

  @Override
  public T save(T object) {
    try {
    final T data = this.entityManager.merge(object);
    return data;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

}

									

A questo punto “estendiamo” l’interfaccia di default di accesso ai dati (genericDao) in modo da rappresentare in maniera più precisa il nostro dominio “user”.

Creiamo l’interfaccia UserDao che estende GenericDao.

UserDao.java

package it.sample.webapp.dao.jpa;

import it.sample.webapp.dao.GenericDao;
import it.sample.webapp.model.User;

/**
 * This interface defines additional data access methods for the <code>User</code>
 * entity.
 */
public interface UserDao extends GenericDao<User, Long>{
  /**
   * Gets the user using specified name
   * @param name name of the user to be searched
   * @return <code>User</code> object retrieved using specified user name
   * @throws javax.persistence.NoResultException when object
   *     corresponding to the specified ID (primary key) is not found. This is a
   *     <code>RuntimeException</code>
   */
  public User getByName(String name);
}

									

Ora possiamo implementare la nostra interfaccia in modo da prelevare i dati di una tupla a partire dall’username.

UserDaoImpl.java

package it.sample.webapp.dao.jpa.impl;

import javax.persistence.Query;

import it.sample.webapp.dao.jpa.BaseJpaDao;
import it.sample.webapp.dao.jpa.UserDao;
import it.sample.webapp.model.User;

public final class UserDaoImpl extends BaseJpaDao<User, Long> implements UserDao{

  public UserDaoImpl() {
    super(User.class);
  }

  @Override
  public User getByUserName(String username) {
    Query q = this.entityManager.createQuery("SELECT u FROM User u where u.username = :username");
    q.setParameter("username", username);
    User u = (User)q.getSingleResult();
    return u;
  }
}