22 April 2012

DAO Example

public interface AnniversaryDao {
  Anniversary getByYear(int years);
}
public class AnniversaryJdbcDao implements AnniversaryDao{
  private static final String GET_BY_YEAR = 
    "SELECT * from Anniversary WHERE years = ?";
  //...
  public Anniversary getByYear(int years) {
    //…
    PreparedStatement statement = connection.prepareStatement(GET_BY_YEAR);
    statement.setInt(1,years);
    ResultSet rs = statement.executeQuery();
    if (rs.next()){
      result = new Anniversary(
      rs.getInt("years"),
      rs.getString("material"),
      rs.getString("flowers"));
    }
   //  ....
  return result;
  }
}
public class AnniversaryJpaSeDao implements AnniversaryDao{
   EntityManagerFactory emf = Persistence
    .createEntityManagerFactory("JPA-03PU");

  private EntityManager getEntityManager() {
    return emf.createEntityManager();
  }
  //...
  public Anniversary getByYear(int years) {
    return getEntityManager().createNamedQuery(findAnniversayByYear)
      .setParameter("years", years)
      .getSingleResult();
  }
}
@ManagedBean
@RequestScoped
public class AnniversaryJpaEe6Dao implements AnniversaryDao{
  @¨PersistenceContext private EntityManager em;

  //...
  public Anniversary getByYear(int years) {
    return em.createNamedQuery(findAnniversayByYear)
      .setParameter("years", years)
      .getSingleResult();
  }
}

No comments:

Post a Comment