`
zhanghong
  • 浏览: 90747 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

JSF2与EJB3,JPA2集成

阅读更多

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;

 

 

0
0
分享到:
评论
1 楼 zhousemi 2011-08-17  
我丝毫没看到Jsf2的标签

相关推荐

Global site tag (gtag.js) - Google Analytics