JSF2与EJB3,JPA2集成_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > JSF2与EJB3,JPA2集成

JSF2与EJB3,JPA2集成

 2011/1/10 9:46:37  zhanghong  http://zhanghong.javaeye.com  我要评论(0)
  • 摘要:JSF2中注解的应用,使得JSF2很容易与EJB3,JPA2集成。首先,定义一个业务接口,作为EJB的一个本地接口:@LocalpublicinterfaceCustomerSessionBeanI{publicCustomergetById(longid);publicList<Customer>findAll();publicvoiddeleteById(longid);publicvoidsave(Customerc);}定义一个SessionBean来实现这个接口
  • 标签:JPA

JSF2中注解的应用,使得JSF2很容易与EJB3,JPA2集成。

?

首先,定义一个业务接口,作为EJB的一个本地接口:

?

@Local
public interface CustomerSessionBeanI {
	public Customer getById(long id);
	public List<Customer> findAll();
	public void deleteById(long id);
	public void save(Customer c);
}

?

定义一个SessionBean来实现这个接口:

?

@Stateless
public class CustomerSessionBean implements CustomerSessionBeanI{

	@PersistenceContext
	private EntityManager em;

	public Customer getById(long id) {
		return em.find(Customer.class, id);
	}

	public void setEm(EntityManager em) {
		this.em = em;
	}

	public EntityManager getEm() {
		return em;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> findAll() {
		return (List<Customer> )em.createNamedQuery("getAll").getResultList();
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void deleteById(long id) {
		Query q = em.createNamedQuery("deleteById");
		q.setParameter(1, id);
		q.executeUpdate();

	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void save(Customer c) {
		em.persist(c);

	}
}

?

生成实体Bean:

?

?

@NamedQueries({
	@NamedQuery(name="getAll",query="select c From Customer c"),
	@NamedQuery(name="deleteById",query="Delete  c from Customer c where id=?1")
})
@Entity
public class Customer implements Serializable {
	private static final long serialVersionUID = 1L;

	@Id
	private long id;

	private int age;

	private String gender;

	private String name;
        
         ............................
}

?

persistence.xml:

?

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
	xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
	<persistence-unit name="jejbClient" transaction-type="JTA">
		<jta-data-source>ora1</jta-data-source>
		<class>com.bond.dom.Customer</class>
		<properties></properties>
	</persistence-unit>
</persistence>

?

在ManagedBean中就可以使用了:

?

@EJB

private CustomerSessionBeanI customerbean;

?

?

发表评论
用户名: 匿名