domingo, 20 de janeiro de 2008

CRUD com JSF e JPA - parte1/3

Neste Tutorial irei mostrar como fazer um CRUD (Create, Read, Update, Delete) utilizando os frameworks JSF(JavaServer Faces) e JPA(Java Persistence API).

Recursos necessários:
IDE de desenvolvimento Java (Netbeans ou Eclipse).
Banco de dados DB2 ou MySQL.
Oracle TopLink Essential (funcionalidades para o JPA), pode ser obtido em : www.oracle.com/technology/jpa

Primeiramente vamos criar o Banco de Dados, abaixo temos uma figura do modelo do banco TUTORIAL e suas SQLs.





Figura 1: TUTORIAL DATABASE






CREATE DATABASE TUTORIAL;
USE TUTORIAL;
CREATE TABLE CITY(
ID INT PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY,
CITY VARCHAR(30));



CREATE TABLE CLIENT(
ID INT PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY,
NAME VARCHAR(50),
ADDRESS VARCHAR(100),
ID_CITY INT,
CONSTRAINT CLI_CITY_FK FOREIGN KEY(ID_CITY) REFERENCES CITY(ID)
);






Agora Utilizando sua IDE preferida devemos criar um novo projeto Web utilizando o framework JSF.
Com o projeto iniciado devemos criar três pacotes e um diretório como mostra a figura 2:
· Pacote – com.tutorialday.controller
· Pacote – com.tutorialday.dao
· Pacote – com.tutorialday.model
· Diretório – META-INF









Figura 2: Estrutura do Projeto





Criaremos agora as classes Entitys (City, Client) no pacote com.tutorialday.model, abaixo segue o source das mesmas.





CLASSE City


package com.tutorialday.model;

import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;


@Entity
@Table(name="city")
public class City {


@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;

@Column(name="city")
private String city;

@OneToMany(cascade=CascadeType.ALL, mappedBy="city")
private Collection client;

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public Collection getClient() {
return client;
}

public void setClient(Collection client) {
this.client = client;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

}


CLASSE Client



package com.tutorialday.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;



@Entity
@Table(name="client")
public class Client {


@Id
@Column(name="id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;

@Column(name="name")
private String name;

@Column(name="address")
private String address;

@ManyToOne
@JoinColumn(name="id_city", nullable = false)
private City city;

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public City getCity() {
return city;
}

public void setCity(City city) {
this.city = city;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

}


Com nossas Classes Entitys pronta, vamos criar agora a classe BaseDao no pacote com.tutorialday.dao , a mesma é uma classe genérica que contém métodos genéricos e métodos específicos para persistência e manipulação dos nossos “objetos”.


CLASSE BaseDao


package com.tutorialday.dao;

import java.util.ArrayList;
import java.util.List;

import javax.faces.model.SelectItem;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.tutorialday.model.City;

public class BaseDao {
private static EntityManagerFactory emf;

private EntityManager getEntityManager(){
return emf.createEntityManager();
}

public BaseDao(){
emf =
Persistence.createEntityManagerFactory("tutorial");
}


// METODO PARA PERSISTIR
public boolean create(T obj){
EntityManager em = getEntityManager();
try{
em.getTransaction().begin();
em.persist(obj);
em.getTransaction().commit();
return true;
}
catch (Exception ex){
ex.printStackTrace();
em.getTransaction().rollback();
return false;
} finally {
em.close();
}
}


// METODO PARA ATUALIZAR
public boolean update(T obj){
EntityManager em = getEntityManager();
try{
em.getTransaction().begin();
em.merge(obj);
em.getTransaction().commit();
return true;
}
catch (Exception ex){
ex.printStackTrace();
em.getTransaction().rollback();
return false;
}
finally {
em.close();
}
}


// METODO PARA EXCLUIR
public boolean delete(T obj){
EntityManager em = getEntityManager();
try{
em.getTransaction().begin();
obj = em.merge(obj);
em.remove(obj);
em.getTransaction().commit();
return true;
}
catch (Exception ex){
ex.printStackTrace();
em.getTransaction().rollback();
return false;
} finally {
em.close();
}
}


// METODO QUE RETORNA UMA LISTA DE CLIENT
public List allClient(){
EntityManager em = getEntityManager();
try{
Query usu = em.createQuery("select object(c) from Client as c");
return usu.getResultList();
}catch(Exception e){
return null;
}finally {
em.close();
}
}



// METODO QUE RETORNA UMA LISTA DE CITY
public List allCity(){
EntityManager em = getEntityManager();
try{
Query cty = em.createQuery("select object(ct) from City as ct");
return cty.getResultList();
}catch(Exception e){
return null;
}finally {
em.close();
}
}



// METODO QUE RETORNA UMA LISTA DE NOMES DE CIDADES
@SuppressWarnings("unchecked")
public List listCity(){
EntityManager em = getEntityManager();
try{
Query city = em.createQuery("select ct.city from City as ct");
List list0 = city.getResultList();
List list = new ArrayList();
int i;
for (i=0; i <>



// METODO QUE RETORNA UM OBJETO CITY PEGANDO COMO PARAMETO O NOME DA CIDADE
@SuppressWarnings("unchecked")
public T findCityByName(String cty){
EntityManager em = getEntityManager();
try{
Query city = em.createQuery("select object(ct) from City as ct where ct.city

like ?1" ).setParameter(1,cty+"%");
return (T) city.getSingleResult();
}catch(Exception e){
return null;
}finally {
em.close();
}
}
}


Na segunda parte iremos dar continuidade deste tutorial com a criação do FacesBean, mapeamento das classes Entitys e fazer a regra de navegação no arquivo faces-config.xml.


=) ...