关于EntityManager的使用

EntityManager

Obtaining an EntityManager in a SessionBean
Before an EntityManager can be used it must be obtained from the container. The EntityManager can be set into your SessionBean by the Container though the @Resource annotation.

@Stateless
public class EmployeeDemoSessionEJB implements EmployeeDemoSession {

    @Resource protected EntityManager em;
    ...
    public EntityManager getEntityManger(){
        return this.em;
    }
    ...
Whenever the SessionBean is accessed an EnityManger will be available in the em attribute.

The EntityManager can also be retreived through a JNDI lookup.


    ...
    public EntityManager getEntityManager() {
        if (em == null}
            try{
                em = (EntityManager)(new InitialContext()).lookup("java:comp/ejb/EntityManager");
            } catch (Exception e){};
        }
        return em;
    }
    ...
Note that in this case the @Resource annotation is not used.

EntityManager persist()
The EntityManager persist(Object entity) API is used to mark a new instance for insert into the Database. It must only be called on new Entities. The value returned from the persist(Object entity) call is the same instance as was passed in.

@Stateless
public class EmployeeDemoSessionEJB implements EmployeeDemoSession {
    ...
    public void createEmployee(String fName, String lName) {
        Employee employee  = new Employee();
        employee.setFirstName(fName);
        employee.setLastName(lName);
        em.persist(employee);
    }
    ...
EntityManager merge()
To integrate a bean read in a different transaction or provided by the client into the current transaction use the merge(Object entity) API. The result will be an instance of the provided entity. The state of that entity will also be available in the returned instance.

@Stateless
public class EmployeeDemoSessionEJB implements EmployeeDemoSession {
    ...
    public void updateAddress(Address addressExample) {
        em.merge(addressExample);
    }
    ...
EntityManager remove()
To delete a bean from the database use the remove(Object entityBean) API.

@Stateless
public class EmployeeDemoSessionEJB implements EmployeeDemoSession {
    ...
    public void removeEmployee(Integer employeeId) {
        Employee employee = (Employee)em.find("Employee", employeeId);
        ...
        em.remove(employee);
    }
    ...
EntityManager find()
When a primary key query is required the find(String entityName, Object primaryKey) or find(Class entityClass, Object primaryKey) API can be used.

@Stateless
public class EmployeeDemoSessionEJB implements EmployeeDemoSession {
    ...
    public void removeEmployee(Integer employeeId) {
        Employee employee = (Employee)em.find("Employee", employeeId);
        ...
        em.remove(employee);
    }
    ...
EntityManager flush()
The EntityManager flush() API is used to send updates to the database within a transaction, subsequent queries within the same transaction will return the updated data. This is usefull if a particular transaction spans mutiple operations or pages, similar to a "wizard".

@Stateless
public class EmployeeDemoSessionEJB implements EmployeeDemoSession {
    ...
    public void terminateEmployee(EmploymentPeriod period, Integer employeeId){
   Employee employee = (Employee)em.find("Employee", employeeId);
       employee.setPeriod(period);
       em.flush();
    ...
EntityManager refresh()
When the latest data is required or when changes need to be reverted in an Entity Bean the refresh(Object entity) API can be used.


...
public void undoUpdateEmployee(Integer employeeId){
Employee employee = (Employee)em.find("Employee", employeeId);
em.refresh(employee);
}
    ...
EntityManager createQuery()
In order to perform queries based on more complex criteria queries can be created using the createQuery(String ejbqlString) or createNamedQuery(String name) see the How To on Queries for more specific information.

@Stateless
public class EmployeeDemoSessionEJB implements EmployeeDemoSession {
    ...
    public Collection findLargeProjectsWithBudgetLargerThan(double budget) {
        Collection projects = em.createNamedQuery("findWithBudgetLargerThan")
             .setParameter("amount", budget).getResultList();
        return projects;
    }

    public Project findOneProjectByQuery(Vector params) {
        Project project = (Project)em.createQuery("SELECT OBJECT(project) FROM Project project WHERE project.name = :projectName")
                .setParameter("projectName", params.firstElement()).getSingleResult();
        return project;
    }
   ...
EntityManager createQuery(Expression)
If TopLink's java like expressions are prefered for the query criteria, that functionality is available though the createQuery(Expression expression, Class resultType) api on the OC4J specific EntityManager implementation oracle.toplink.ejb.cmp3.EntityManager.

@Stateless
public class EmployeeDemoSessionEJB implements EmployeeDemoSession {
    ...
    public Collection findManyProjectsByQuery(Vector params) {
        ExpressionBuilder builder = new ExpressionBuilder();
        Query query = ((oracle.toplink.ejb.cmp3.EntityManager)em)
            .createQuery(builder.get("name").equals(builder.getParameter("projectName")), Project.class);
        query.setParameter("projectName", params.firstElement());
        Collection projects = query.getResultList();
        return projects;
    }
    ...

你可能感兴趣的:(oracle,bean,ejb)