7 Replies Latest reply on Oct 7, 2006 6:12 PM by johnurban

    Access SFSB from another SFSB using Injection...

    johnurban

      Another Design Question...

      - SFSB_1 is instaciated and tied to a JSF.
      - When a particular event occurs inside SFSB_1, I want to call a create() method in SFSB_2.
      - SFSB_2 has not be instianciated. In fact the event that fired inside SFSB_1 has all of the data needed to create a POJO Entity Bean that is tied to SFSB_2.

      What I am trying to do:

      I am attempting to record attendance(attendance record/pojo/SFSB_2) on a student record/pojo/SFSB_1. When I click on a "checkin" button, I want to scrape some data from the student object and create/add/insert a new attendance record.

      Question:

      I am going about this correctly? If not, what is the best way to add a record to a table/pojo/SFSB_2 from inside this SFSB_1.

        • 1. Re: Access SFSB from another SFSB using Injection...
          pmuir

          I'm not sure what

          - SFSB_1 is instaciated and tied to a JSF.


          or

          - SFSB_2 has not be instianciated. In fact the event that fired inside SFSB_1 has all of the data needed to create a POJO Entity Bean that is tied to SFSB_2.


          means. Apart from that why not do

          @Name("sfsb1")
          public class SFSB_1 {
          
          // Inject any objects
          
          @In(create=true)
          private SFSB_2 sfsb2;
          ...
          
          public String checkin() {
           // Stuff
           sfsb2.create();
           // Stuff
           return "something";
          }
          ...
          }


          @Name("sfsb2")
          public class SFSB_2 {
          ...
          // Inject any objects
          
          public void create() {
           // Stuff
          }
          ...
          }


          Any help?

          • 2. Re: Access SFSB from another SFSB using Injection...
            johnurban

            What if SFSB_2 has not yet been created? Here is what i am trying to do. I have 3 tables: Person, Room and Attendance. I used the reverse engineer hibernate tool to build JBoss seam framework for all 3. I have added a check box to the findPerson jsf such that when they click on that I need to create an Attendance record from the PersonFinderBean SFSB EJB. The Attendance record has PersonId, RoomId and some other fields.

            How do I create that Attendance record from the within the PersonFinderBean EJB?

            • 3. Re: Access SFSB from another SFSB using Injection...
              pmuir

               

              What if SFSB_2 has not yet been created?


              This is why I did

              [qupte]
              @In(create=true)
              private SFSB_2 sfsb2;


              • 4. Re: Access SFSB from another SFSB using Injection...
                pmuir

                Sorry, that was a mangled mess :(

                ----

                What if SFSB_2 has not yet been created?


                This is why I did

                @In(create=true)
                private SFSB_2 sfsb2;


                I suggest you post some code - makes it much easier to understand where you are having problems! In general I would suggest grouping related functions on the same sesion bean - perhaps you should use a different session bean for creating that attendance record?

                • 5. Re: Access SFSB from another SFSB using Injection...
                  johnurban

                  This, obviously does not work (look at the checkIn() method:

                  PersonFinderBean.java

                  package testSeam;
                  
                  // Generated Sep 23, 2006 1:30:01 PM by Hibernate Tools 3.2.0.beta7
                  
                  import java.util.HashMap;
                  import java.util.List;
                  import java.util.Map;
                  import java.util.Map.Entry;
                  import java.util.Random;
                  import java.util.Date;
                  import javax.ejb.Remove;
                  import javax.ejb.Stateful;
                  import javax.interceptor.Interceptors;
                  import javax.persistence.EntityManager;
                  import javax.persistence.Query;
                  import org.jboss.seam.ScopeType;
                  import org.jboss.seam.annotations.Destroy;
                  import org.jboss.seam.annotations.In;
                  import org.jboss.seam.annotations.Name;
                  import org.jboss.seam.annotations.RequestParameter;
                  import org.jboss.seam.annotations.Scope;
                  import org.jboss.seam.annotations.datamodel.DataModel;
                  import org.jboss.seam.annotations.datamodel.DataModelSelection;
                  import org.jboss.seam.ejb.SeamInterceptor;
                  
                  @Name("personFinder")
                  @Stateful
                  @Scope(ScopeType.SESSION)
                  @Interceptors(SeamInterceptor.class)
                  public class PersonFinderBean implements PersonFinder {
                  
                   private Person example = new Person();
                  
                   public Person getExample() {
                   return example;
                   }
                  
                   Users instance = new Users();
                  
                   @In(required=false)
                   private Login login;
                  
                   private AttendanceEditor attendanceRecord = ;
                  
                   private int pageNumber = 0;
                   private int pageSize = 20;
                   private boolean registered = false;
                  
                   public String getSecurityCode() {
                   return "83738392";
                   }
                  
                   public void setRegistered(boolean value) {
                   registered = value;
                   }
                  
                   public boolean getRegistered() {
                   return registered;
                   }
                  
                   public void setPageSize(int size) {
                   pageSize = size;
                   }
                  
                   public int getPageSize() {
                   return pageSize;
                   }
                  
                   public boolean isPreviousPage() {
                   return personList != null && pageNumber > 0;
                   }
                  
                   public boolean isNextPage() {
                   return personList != null && personList.size() == pageSize;
                   }
                  
                   @DataModel
                   private List<Person> personList;
                  
                   @DataModelSelection
                   private Person selectedPerson;
                  
                   @In(create = true)
                   private EntityManager entityManager;
                  
                   private void executeQuery() {
                   Map<String, Object> parameters = new HashMap<String, Object>();
                   StringBuffer queryString = new StringBuffer();
                   if (example.getId() != 0) {
                   queryString.append(" and person.id = :id");
                   parameters.put("id", example.getId());
                   }
                   if (example.getRoomId() != 0) {
                   queryString.append(" and person.roomId = :roomId");
                   parameters.put("roomId", example.getRoomId());
                   }
                   if (example.getOrganizationId() != 0) {
                   queryString.append(" and person.organizationId = :organizationId");
                   parameters.put("organizationId", example.getOrganizationId());
                   }
                   if (example.getFirstName() != null && example.getFirstName().length() > 0) {
                   queryString.append(" and person.firstName like :firstName");
                   parameters.put("firstName", '%' + example.getFirstName() + '%');
                   }
                   if (example.getMiddleName() != null
                   && example.getMiddleName().length() > 0) {
                   queryString.append(" and person.middleName like :middleName");
                   parameters.put("middleName", '%' + example.getMiddleName() + '%');
                   }
                   if (example.getLastName() != null && example.getLastName().length() > 0) {
                   queryString.append(" and person.lastName like :lastName");
                   parameters.put("lastName", '%' + example.getLastName() + '%');
                   }
                   if (example.getAddress1() != null && example.getAddress1().length() > 0) {
                   queryString.append(" and person.address1 like :address1");
                   parameters.put("address1", '%' + example.getAddress1() + '%');
                   }
                   if (example.getCity() != null && example.getCity().length() > 0) {
                   queryString.append(" and person.city like :city");
                   parameters.put("city", '%' + example.getCity() + '%');
                   }
                   if (example.getState() != null && example.getState().length() > 0) {
                   queryString.append(" and person.state like :state");
                   parameters.put("state", '%' + example.getState() + '%');
                   }
                   if (example.getZip() != null && example.getZip().length() > 0) {
                   queryString.append(" and person.zip like :zip");
                   parameters.put("zip", '%' + example.getZip() + '%');
                   }
                   if (example.getEmail() != null && example.getEmail().length() > 0) {
                   queryString.append(" and person.email like :email");
                   parameters.put("email", '%' + example.getEmail() + '%');
                   }
                   if (example.getBirthday() != null) {
                   queryString.append(" and person.birthday = :birthday");
                   parameters.put("birthday", example.getBirthday());
                   }
                   if (example.getSex() != null) {
                   queryString.append(" and person.sex = :sex");
                   parameters.put("sex", example.getSex());
                   }
                   if (example.getHomePhone() != null
                   && example.getHomePhone().length() > 0) {
                   queryString.append(" and person.homePhone like :homePhone");
                   parameters.put("homePhone", '%' + example.getHomePhone() + '%');
                   }
                   if (example.getWorkPhone() != null
                   && example.getWorkPhone().length() > 0) {
                   queryString.append(" and person.workPhone like :workPhone");
                   parameters.put("workPhone", '%' + example.getWorkPhone() + '%');
                   }
                   if (example.getBeeperPhone() != null
                   && example.getBeeperPhone().length() > 0) {
                   queryString.append(" and person.beeperPhone like :beeperPhone");
                   parameters.put("beeperPhone", '%' + example.getBeeperPhone() + '%');
                   }
                   if (example.getCellPhone() != null
                   && example.getCellPhone().length() > 0) {
                   queryString.append(" and person.cellPhone like :cellPhone");
                   parameters.put("cellPhone", '%' + example.getCellPhone() + '%');
                   }
                   if (example.getExtraPhone() != null
                   && example.getExtraPhone().length() > 0) {
                   queryString.append(" and person.extraPhone like :extraPhone");
                   parameters.put("extraPhone", '%' + example.getExtraPhone() + '%');
                   }
                   if (example.getExtraPhoneMemo() != null
                   && example.getExtraPhoneMemo().length() > 0) {
                   queryString
                   .append(" and person.extraPhoneMemo like :extraPhoneMemo");
                   parameters.put("extraPhoneMemo",
                   '%' + example.getExtraPhoneMemo() + '%');
                   }
                   if (example.getSchool() != null && example.getSchool().length() > 0) {
                   queryString.append(" and person.school like :school");
                   parameters.put("school", '%' + example.getSchool() + '%');
                   }
                   if (example.getSchoolGrade() != null
                   && example.getSchoolGrade().length() > 0) {
                   queryString.append(" and person.schoolGrade like :schoolGrade");
                   parameters.put("schoolGrade", '%' + example.getSchoolGrade() + '%');
                   }
                   if (example.getContact() != null && example.getContact().length() > 0) {
                   queryString.append(" and person.contact like :contact");
                   parameters.put("contact", '%' + example.getContact() + '%');
                   }
                   if (example.getParentName() != null
                   && example.getParentName().length() > 0) {
                   queryString.append(" and person.parentName like :parentName");
                   parameters.put("parentName", '%' + example.getParentName() + '%');
                   }
                   if (example.getComments() != null && example.getComments().length() > 0) {
                   queryString.append(" and person.comments like :comments");
                   parameters.put("comments", '%' + example.getComments() + '%');
                   }
                   if (example.getMinsitry() != null && example.getMinsitry().length() > 0) {
                   queryString.append(" and person.minsitry like :minsitry");
                   parameters.put("minsitry", '%' + example.getMinsitry() + '%');
                   }
                   if (example.getDrama() != null) {
                   queryString.append(" and person.drama = :drama");
                   parameters.put("drama", example.getDrama());
                   }
                   if (example.getMusic() != null) {
                   queryString.append(" and person.music = :music");
                   parameters.put("music", example.getMusic());
                   }
                   if (example.getStatus() != null) {
                   queryString.append(" and person.status = :status");
                   parameters.put("status", example.getStatus());
                   }
                   if (example.getVisitor() != null) {
                   queryString.append(" and person.visitor = :visitor");
                   parameters.put("visitor", example.getVisitor());
                   }
                   if (example.getMailList() != null) {
                   queryString.append(" and person.mailList = :mailList");
                   parameters.put("mailList", example.getMailList());
                   }
                   if (example.getLeader() != null) {
                   queryString.append(" and person.leader = :leader");
                   parameters.put("leader", example.getLeader());
                   }
                   if (example.getLastAttended() != null) {
                   queryString.append(" and person.lastAttended = :lastAttended");
                   parameters.put("lastAttended", example.getLastAttended());
                   }
                   if (example.getCreated() != null) {
                   queryString.append(" and person.created = :created");
                   parameters.put("created", example.getCreated());
                   }
                   if (example.getUpdated() != null) {
                   queryString.append(" and person.updated = :updated");
                   parameters.put("updated", example.getUpdated());
                   }
                   if (example.getVcall() != null) {
                   queryString.append(" and person.vcall = :vcall");
                   parameters.put("vcall", example.getVcall());
                   }
                   if (example.getVhouseCall() != null) {
                   queryString.append(" and person.vhouseCall = :vhouseCall");
                   parameters.put("vhouseCall", example.getVhouseCall());
                   }
                   if (example.getTeam() != null && example.getTeam().length() > 0) {
                   queryString.append(" and person.team like :team");
                   parameters.put("team", '%' + example.getTeam() + '%');
                   }
                   if (example.getPhotoFile() != null
                   && example.getPhotoFile().length() > 0) {
                   queryString.append(" and person.photoFile like :photoFile");
                   parameters.put("photoFile", '%' + example.getPhotoFile() + '%');
                   }
                   if (example.getUniqueId() != null && example.getUniqueId().length() > 0) {
                   queryString.append(" and person.uniqueId like :uniqueId");
                   parameters.put("uniqueId", '%' + example.getUniqueId() + '%');
                   }
                   if (queryString.length() == 0) {
                   queryString.append("select person from Person person");
                   } else {
                   queryString.delete(0, 4).insert(0,
                   "select person from Person person where");
                   }
                  
                   if (order != null) {
                   queryString.append(" order by person.").append(order);
                   if (descending)
                   queryString.append(" desc");
                   }
                  
                   Query query = entityManager.createQuery(queryString.toString());
                   for (Entry<String, Object> param : parameters.entrySet()) {
                   query.setParameter(param.getKey(), param.getValue());
                   }
                   personList = (List<Person>) query.setMaxResults(pageSize)
                   .setFirstResult(pageSize * pageNumber).getResultList();
                   }
                  
                   public String findFirstPage() {
                   pageNumber = 0;
                   executeQuery();
                   return null;
                   }
                  
                   public String findNextPage() {
                   pageNumber++;
                   executeQuery();
                   return null;
                   }
                  
                   public String findPreviousPage() {
                   pageNumber--;
                   executeQuery();
                   return null;
                   }
                  
                   public void refresh() {
                   if (personList != null)
                   executeQuery();
                   }
                  
                   public String clear() {
                   personList = null;
                   example = new Person();
                   return null;
                   }
                  
                   public Person getSelection() {
                   return entityManager.merge(selectedPerson);
                   }
                  
                   @Destroy
                   @Remove
                   public void destroy() {
                   }
                  
                   private String order;
                  
                   private boolean descending = false;
                  
                   @RequestParameter
                   private String orderBy;
                   private int id;
                  
                   public String reorder() {
                   if (orderBy.equals(order)) {
                   descending = !descending;
                   } else {
                   descending = false;
                   }
                   order = orderBy;
                   executeQuery();
                   return null;
                   }
                  
                   public String checkIn() {
                   int parmId = id;
                   // insert new record into attendance table
                   System.out.println("I check'd em in...:"+id);
                   System.out.println("I am from church:"+login.getInstance().getOrganizationId());
                   int organization = login.getInstance().getOrganizationId();
                  
                   java.util.Random rNum = new Random(123456);
                   Attendance attend = attendanceRecord.getInstance();
                  
                   attend.setCheckedByUserId(login.getInstance().getId());
                   attend.setDateTimeEntry(new Date());
                   attend.setPersonId(example.getId());
                   attend.setRoomId(example.getRoomId());
                   attend.setSecurityCode(""+rNum.nextInt());
                   attend.setType("In");
                   attendanceRecord.create();
                  
                   return "code:"+rNum.nextInt();
                   }
                  }
                  
                  


                  Here is the AttendanceEditorBean.java:

                  
                  package testSeam;
                  
                  // Generated Oct 6, 2006 12:57:37 AM by Hibernate Tools 3.2.0.beta7
                  
                  import java.util.Map;
                  import javax.ejb.Remove;
                  import javax.ejb.Stateful;
                  import javax.ejb.TransactionAttribute;
                  import static javax.ejb.TransactionAttributeType.NOT_SUPPORTED;
                  import javax.faces.application.FacesMessage;
                  import javax.faces.context.FacesContext;
                  import javax.interceptor.Interceptors;
                  import javax.persistence.EntityManager;
                  import org.hibernate.validator.Valid;
                  import org.jboss.seam.annotations.Begin;
                  import org.jboss.seam.annotations.Destroy;
                  import org.jboss.seam.annotations.End;
                  import org.jboss.seam.annotations.IfInvalid;
                  import org.jboss.seam.annotations.In;
                  import org.jboss.seam.annotations.Name;
                  import org.jboss.seam.annotations.Outcome;
                  import org.jboss.seam.ejb.SeamInterceptor;
                  
                  @Name("attendanceEditor")
                  @Stateful
                  @Interceptors(SeamInterceptor.class)
                  public class AttendanceEditorBean implements AttendanceEditor {
                  
                   @In(create = true)
                   private EntityManager entityManager;
                  
                   @Valid
                   private Attendance instance = new Attendance();
                  
                   @TransactionAttribute(NOT_SUPPORTED)
                   public Attendance getInstance() {
                   return instance;
                   }
                  
                   public void setInstance(Attendance instance) {
                   this.instance = instance;
                   }
                  
                   private boolean isNew = true;
                  
                   @TransactionAttribute(NOT_SUPPORTED)
                   public boolean isNew() {
                   return isNew;
                   }
                  
                   public void setNew(boolean isNew) {
                   this.isNew = isNew;
                   }
                  
                   private String doneOutcome = "find";
                  
                   public void setDoneOutcome(String outcome) {
                   doneOutcome = outcome;
                   }
                  
                   @In(required = false)
                   private transient AttendanceFinder attendanceFinder;
                  
                   @In(create = true)
                   private transient Map messages;
                  
                   @Begin(join = true)
                   @IfInvalid(outcome = Outcome.REDISPLAY)
                   public String create() {
                   if (entityManager.find(Attendance.class, instance.getId()) != null) {
                   FacesContext.getCurrentInstance().addMessage(
                   null,
                   new FacesMessage(messages.get("Attendance_id") + " "
                   + messages.get("AlreadyExists")));
                   return null;
                   }
                   entityManager.persist(instance);
                   isNew = false;
                   refreshFinder();
                   return "editAttendance";
                   }
                  
                   @IfInvalid(outcome = Outcome.REDISPLAY)
                   public String update() {
                   refreshFinder();
                   return null;
                   }
                  
                   @End(ifOutcome = "find")
                   public String delete() {
                   entityManager.remove(instance);
                   refreshFinder();
                   return doneOutcome;
                   }
                  
                   @End(ifOutcome = "find")
                   public String done() {
                   if (!isNew)
                   entityManager.refresh(instance);
                   return doneOutcome;
                   }
                  
                   private void refreshFinder() {
                   if (attendanceFinder != null)
                   attendanceFinder.refresh();
                   }
                  
                   @Destroy
                   @Remove
                   public void destroy() {
                   }
                  
                  }
                  


                  Here is the Attenance.java Entity:

                  
                  package testSeam;
                  
                  // Generated Oct 6, 2006 12:57:37 AM by Hibernate Tools 3.2.0.beta7
                  
                  import java.util.Date;
                  import javax.persistence.Column;
                  import javax.persistence.Entity;
                  import javax.persistence.Id;
                  import javax.persistence.Table;
                  
                  /**
                   * Attendance generated by hbm2java
                   */
                  @Entity
                  @Table(name = "attendance", catalog = "checkin", uniqueConstraints = {})
                  public class Attendance implements java.io.Serializable {
                  
                   // Fields
                  
                   private int id;
                  
                   private String type;
                  
                   private int personId;
                  
                   private Date dateTimeEntry;
                  
                   private int checkedByUserId;
                  
                   private String securityCode;
                  
                   private int roomId;
                  
                   // Constructors
                  
                   /** default constructor */
                   public Attendance() {
                   }
                  
                   /** full constructor */
                   public Attendance(int id, String type, int personId, Date dateTimeEntry,
                   int checkedByUserId, String securityCode, int roomId) {
                   this.id = id;
                   this.type = type;
                   this.personId = personId;
                   this.dateTimeEntry = dateTimeEntry;
                   this.checkedByUserId = checkedByUserId;
                   this.securityCode = securityCode;
                   this.roomId = roomId;
                   }
                  
                   // Property accessors
                   @Id
                   @Column(name = "ID", unique = true, nullable = false, insertable = true, updatable = true)
                   public int getId() {
                   return this.id;
                   }
                  
                   public void setId(int id) {
                   this.id = id;
                   }
                  
                   @Column(name = "Type", unique = false, nullable = false, insertable = true, updatable = true, length = 10)
                   public String getType() {
                   return this.type;
                   }
                  
                   public void setType(String type) {
                   this.type = type;
                   }
                  
                   @Column(name = "PersonID", unique = false, nullable = false, insertable = true, updatable = true)
                   public int getPersonId() {
                   return this.personId;
                   }
                  
                   public void setPersonId(int personId) {
                   this.personId = personId;
                   }
                  
                   @Column(name = "DateTimeEntry", unique = false, nullable = false, insertable = true, updatable = true, length = 19)
                   public Date getDateTimeEntry() {
                   return this.dateTimeEntry;
                   }
                  
                   public void setDateTimeEntry(Date dateTimeEntry) {
                   this.dateTimeEntry = dateTimeEntry;
                   }
                  
                   @Column(name = "CheckedByUserId", unique = false, nullable = false, insertable = true, updatable = true)
                   public int getCheckedByUserId() {
                   return this.checkedByUserId;
                   }
                  
                   public void setCheckedByUserId(int checkedByUserId) {
                   this.checkedByUserId = checkedByUserId;
                   }
                  
                   @Column(name = "SecurityCode", unique = false, nullable = false, insertable = true, updatable = true, length = 50)
                   public String getSecurityCode() {
                   return this.securityCode;
                   }
                  
                   public void setSecurityCode(String securityCode) {
                   this.securityCode = securityCode;
                   }
                  
                   @Column(name = "RoomId", unique = false, nullable = false, insertable = true, updatable = true)
                   public int getRoomId() {
                   return this.roomId;
                   }
                  
                   public void setRoomId(int roomId) {
                   this.roomId = roomId;
                   }
                  
                  }
                  


                  • 6. Re: Access SFSB from another SFSB using Injection...
                    pmuir

                    Sorry, what doesn't work? What exception do you get?

                    I don't really understand the code (e.g. it seems that Person example is an entity but nowhere do you load/inject it, just do a pojo instantiation; I would expect associations rather than ids to link objects), but the checkin method itself seems fine in concept:

                    1) Ask attendanceEditor for a new attendance record
                    2) Populate it
                    3) Tell attendanceEditor to persist it

                    • 7. Re: Access SFSB from another SFSB using Injection...
                      johnurban

                      Thanks. All I needed to see was:


                      1) Ask attendanceEditor for a new attendance record


                      And that did it.