Ce billet est la suite de Utiliser un formulaire Web- Tutorial Seam partie 4
Créer une entity Animal
Pour persister les données et représenter les objets métiers, Seam utilise des Entity EJB3. Ces entity font partie de la partie « model » du projet.
Notre entity va s’appeler animal et représente un animal.
Dans eclipse, dans le projet, dans l’onglet Project Explorer, sélectionner src/model, faire un clique droit. Choisir New Class. Dans le champs package écrire com.getj2ee.tuto.seam.helloworld.model et dans le champs Name écrire Animal. Cliquez sur next.
Modifier la classe pour arriver à ceci :
package com.getj2ee.tuto.seam.helloworld.model;
import java.io.Serializable;
import static org.jboss.seam.ScopeType.SESSION;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.NotNull;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
@Entity
@Name("animal")
@Table(name = "animals")
public class Animal implements Serializable {
private static final long serialVersionUID = 1881413500711441952L;
@Id @GeneratedValue
private Long id;
@NotNull
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
La déclaration d’un bean entity se fait grâce à l’annotation @Entity.
@Name est le nom du bean entity dans le contexte du serveur.
@Table (name = « animals ») permet de préciser que cette entity sera stockée dans la table animals.
Chaque entity doit avoir un id unique. La notation
@Id @GeneratedValue
private Long id
Signifie que l’id de cette entity est le champs id de la classe et qu’il est généré automatiquement par la base de données.
Créer une interface Action
Cette interface décrit les actions possibles sur une entity Animal. Créer une classe AnimalsAction qui contiendra ce code :
package com.getj2ee.tuto.seam.helloworld.action;
import java.util.List;
import javax.ejb.Local;
import com.getj2ee.tuto.seam.helloworld.model.Animal;
@Local
public interface AnimalsAction
{
public String saveUpdate();
public List<Animal> getAllAnimals();
}
Créer une classe Action
Cette classe action va permettre de faire toutes les actions de persistance concernant l’entité Animal. Cette classe est une implémentation d’AnimalAction.
Dans eclipse, dans le projet, dans l’onglet Project Explorer, sélectionner src/model et faire un clique droit. Choisir New Class. Dans le champs package écrire com.getj2ee.tuto.seam.helloworld.action et dans le champs Name écrire AnimalsAction. Cliquez sur next.
Modifier la classe pour arriver à ceci :
package com.getj2ee.tuto.seam.helloworld.action;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import com.getj2ee.tuto.seam.helloworld.model.Animal;
@Stateless
@Name("animalsAction")
public class AnimalsActionBean implements AnimalsAction {
@In
private Animal animal;
@PersistenceContext
private EntityManager em;
@Logger
private Log log;
public String saveUpdate() {
List<Animal> existing = em.createQuery("select a from Animal a where name=#{animal.name}").getResultList();
if (existing.size() == 0) {
em.persist(animal);
log.info("Registered new name #{animal.name}");
return "/registered.xhtml";
} else {
FacesMessages.instance().add("Animal #{animal.name} already exists");
return null;
}
}
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
public List<Animal> getAllAnimals() {
List<Animal> animals = em.createQuery("select a from Animal a").getResultList();
return animals;
}
}
AnimalActionBean est un bean stateless, c a d sans état. Il est recréé à chaque utilisation.
La notation @In private Animal animal ; précise qu’un entity animal est injecter dans animalActions
@PersistanceContext private EntityManager em ; désigne l’entityManager qui sera utilisé pour la persistance des entity .
La méthode saveUpdate permet de sauvegarder l’animal. Ceci se fait via l’instruction : em.persist(animal).
La méthode getAllAnimals() retourne tous les animal de la base de données. L’entity manager permet de faire des requêtes : em.createQuery("select a from Animal a").getResultList()
Injecter actionAnimals dans crudAnimals
Modifier le code de crudsAnimals pour obtenir ceci :
package com.getj2ee.tuto.seam.helloworld;
import java.util.List;
import javax.ejb.Stateless;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.log.Log;
import com.getj2ee.tuto.seam.helloworld.action.AnimalsAction;
import com.getj2ee.tuto.seam.helloworld.model.Animal;
@Stateless
@Name("crudAnimals")
public class CrudAnimalsBean implements CrudAnimals {
@Logger
private Log log;
@In()
FacesMessages facesMessages;
@In(create = true)
AnimalsAction animalsAction;
@In(create = true)
private Animal animal;
private String name = "No name";
public void crudAnimals() {
// implement your business logic here
log.info("crudAnimals.crudAnimals() action called");
animal.setName(this.name);
animalsAction.saveUpdate();
facesMessages.add("crudAnimals");
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
log.info("change name in my bean :" + name);
this.name = name;
}
public AnimalsAction getAnimalsAction() {
return animalsAction;
}
public void setAnimalsAction(AnimalsAction animalsAction) {
this.animalsAction = animalsAction;
}
// add additional action methods
public Animal getAnimal() {
return animal;
}
public void setAnimal(Animal animal) {
this.animal = animal;
}
@Override
public List<Animal> getAllAnimals() {
return animalsAction.getAllAnimals();
}
}
L’injection de animal action se fait via cette annotation: @In(create = true) private AnimalsAction animalAction . La notation create = true précise que le bean animalAction sera créé si aucun bean n’est disponible pour l’injection
L’entity animal est injecter via @In(create = true) .
La ligne animalsAction.saveUpdate(); sauvegarde l’entity animal.
Afficher tous les « animals » dans un datatable
Modifions la page crudAnimals.xhtml pour faire apparaitre la liste de tous les animaux qui sont dans la base de données.
Juste après la dernière balise </h :form> ajouter ceci :
<h:dataTable value="#{crudAnimals.allAnimals}" var="oneAnimal"
rendered="true">
<h:column>
<f:facet name="header">
<h:outputText value="Id" />
</f:facet>
<h:outputText value="#{oneAnimal.id}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Name" />
</f:facet>
<h:outputText value="#{oneAnimal.name}"></h:outputText>
</h:column>
</h:dataTable>
Redéployer et tester
Dans le script Ant, déclencher la target deploy. Aller à l’url http://localhost:8080/helloworld/crudAnimals.seam , il est maintenant possible d’ajouter autant d’animaux que l’on veut.
Références :
Tuto seam Partie 1 : Installer SEAM et JBoss
Tuto seam Partie 2 : Creer un projet SEAM
Tuto seam Partie 3 : Créer une première page web - Tutorial Seam partie 3
Tuto seam Partie 4 : Utiliser un formulaire Web- Tutorial Seam partie 4
EL JSF et JSP : jsf and jsp expression language
La doc de seam : http://www.seamframework.org/Documentation