关于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;
}
...
第一次写博客,那是因为我想与大家分享.Net世界.我原来是ASP程序员,与.Net结缘那是在两年多前.第一次接触它,就喜欢上了.哈哈 接着我给大家分享一下我在项目中用到的数据访问层,这个是我用微软网站上得到的DBHepler数据库访问层的一次改编,让它支持实体类和用表达 式的方式生成SQL,而且更关键的是,他是采用参数的方式传值的,这样就避免了SQL的注入啦.. 以下是这个项目的结构 [SuperDAL] ---DbHelper.cs(来自MSDN的数据访问层) ---EntityManager.cs(实体类管理) ---Expressions.cs(实体类表达式查询) ---Expression.cs(实体类表达式) ---OrderByExpressions.cs(排序表达式查询) ---OrderByExpression.cs(排序表达式) ---ObjectValues -------OrderBy.cs(排序枚举类) ---DBManager.cs(数据访问类管理) ---DbParams.cs(数据库访问类参数) ---DataTableExtensions.cs(这个就是顾名思义啦,DataTable传实体类) 在这里最主要介绍的就是EntityManager这个啦,使用方法如下: 有数据库DB的一张表Customs CREATE TABLE [Customs] ( [Name] [varchar] (20) , [Password] [varchar] (20) , [Email] [varchar] (50) , [Phone] [varchar] (11) NULL , [Old] [int] , [Birthday] [DateTime] ) 有个实体类Customs.cs,结构如下: public class Customs { public string Name {get;set;} public string Password {get;set;} public string Email {get;set;} public string Phone {get;set;} public int Old{get;set} public DateTime Brithday {get;set;} } 数据库表与实体Customs结构是一一对应的.有了实体类CUstoms,下面就可以操作实体类跟操作数据库一样的啦,我们新建一个实体类管理类 CustomsManager.cs public class CustomsManager:EntityManager { public Customs GetByName(string name) { //创建表达式Expressions Expressions exps=new Expressions(); //向表达式添加条件 exps.Eq("name",name); //根据条件查询返回实体类 return EM_GetUnique(exps); } public List SearchByName(string name) { //同样像上面一样建立表达式类 Expressions exps=new Expressions(); exps.Like("name",name);//当然,有年朋友会说如果我要姓为"陈"的,那有些人的名字带陈的怎么办,没关系,可以改为 exps.LeftLike ("name",name); //根据条件查询返回实体类 return EM_GetEntity(exps); } /// /// 登录 /// /// 用户名 /// 密码 public List Login(string name,string password) { Expressions exps=new Expressions(); exps.Eq("name",name); exps.Eq("password",password); return EM_GetEntity(exps); } /// /// 选择年龄大于指定岁数的,并按年龄从小到大排序 /// /// 年龄 public List SelectOlder(int old) { Expressions exps=new Expressions(); exps.Gt("old",old); exp.OrderBys.Add("old", OrderBy.Asc); return EM_GetEntity(exps); } /// /// 选择年龄大于小于指定岁数段的,并按年龄从小到大,姓名从字母升序排序 /// /// 年龄 public List SelectByOld(int oldStart,int oldend) { Expressions exps=new Expressions(); exps.Between("old",oldStart,oldEnd); exp.OrderBys.Add("old", OrderBy.Asc); exp.OrderBys.Add("name",OrderBy.Asc); return EM_GetEntity(exps); } #region 增删改 操作 /// /// 更新操作 /// /// 实体类 public int Update(Customs customs) { return EM_Save(customs);//返回更新的记录数,当然,一般成功执行就会返回1;也可以改上面为public void Update(Customs customs) } /// /// 删除操作 /// /// public int DeleteByName(string name) { Expressions exps=new Expressions(); exps.Eq("name",name); return EM_Delete(exps); } /// /// 删除操作 /// /// 实体类 public int Save(Customs custom) { return EM_Save(custom); } #endregion } 当然还有更多的也就不一一贴出来了 Expressions支持的表达式有 1. Eq (等于)[name=value] 2. NotEq (不等于)[not name = value] 3. Ge (大于等于)[name >=value] 4. Gt (大于)[name>value] 5. Le (小于等于)[name<=value] 6. Lt (小于)[name<value] 7. In (包括)[name in (value)] 8. NotIn (不包括)[not name in (value) 9. IsNotNull (不为NULL)[not name is null] 10. IsNull (等于NULL)[name is null] 11. Between (之间)[name between valueStart and valueEnd] 12. Like (模糊) [name like ‘%value%’ ] 13. LeftLike (左模糊) [name like ‘%value’] 14. RightLike (右模糊) [name like ‘value%’] 其它功能待与Net爱好者探讨啦,希望你有更好的思路
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值