因此,假设我有一个名为Company的JSF托管bean。这个bean也是一个JPA实体类。它看起来像这样:
package com.microtekcomputers.models;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
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 com.microtekcomputers.services.DaoCompany;
@Entity
@ManagedBean
@ViewScoped
public class Company implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int company_id;
@ManagedProperty("#{companyService}")
private DaoCompany daoCompany;
@Column
private String name;
private String address1;
private String address2;
private String city;
private String state;
private String zipcode;
private String contact;
private String tel1;
private String tel2;
private String fax;
private String comments;
//collection of networks, ISPs, software, hardware
@OneToMany(mappedBy="company")
private Set<Network> networks = new HashSet<Network>();
@OneToMany(mappedBy="company")
private Set<ISP> isps = new HashSet<ISP>();
@OneToMany(mappedBy="company")
private Set<Software> softwares = new HashSet<Software>();
@OneToMany(mappedBy="company")
private Set<Hardware> hardwares = new HashSet<Hardware>();
/* I deleted the other getters and setters (but they go here) */
//I NEED THE SETTER FOR MY MANAGED PROPERTY
public void setDaoCompany(DaoCompany daoCompany) {
this.daoCompany = daoCompany;
}
//dao methods
public void insertCompany()
{
daoCompany = new DaoCompany();
daoCompany.insertCompany(this);
}
}
这个想法是为用户提供一个表单来写公司数据(名称,地址,城市等),在提交按钮上,我会调用 insertCompany()。我的DaoCompany类有一个ManagedProperty。这是代码:
package com.microtekcomputers.services;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.microtekcomputers.models.Company;
@ManagedBean(name="companyService")
@ApplicationScoped
public class DaoCompany {
//I created a singleton class for my Session Factory
private SessionFactory sf = SingletonSessionFactory.getSessionFactory();
private Session session = sf.openSession();
public void insertCompany(Company company)
{
Transaction t = session.beginTransaction();
session.save(company);
t.commit();
session.flush();
session.close();
}
public void updateCompany(Company company)
{
Transaction t = session.beginTransaction();
session.update(company);
t.commit();
session.flush();
session.close();
}
}
我的问题是,在同一个类上同时使用JSF托管bean和JPA实体是否是一种好习惯。如果没有,那可能是我的另类选择?因为我不能在我的bean类上使用 insertCompany()来访问xhtml吗?