本站首页    管理页面    写新日志    退出


«January 2026»
123
45678910
11121314151617
18192021222324
25262728293031


公告
 本博客在此声明所有文章均为转摘,只做资料收集使用。

我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:
日志总数:1304
评论数量:2242
留言数量:5
访问次数:7695654
建立时间:2006年5月29日




[Hibernate]在JSE环境中使用Hibernate EntityManger
软件技术

lhwork 发表于 2006/7/14 16:57:05

大家都知道在EJB3中 使用EntityManger来操作持久化数据,Hibernate也实现了与EJB3完全兼容并且功能更强的EntityManger,配合Hibernate Annotation一起使用 可以说在数据持久化方面与EJB3几乎没有区别了,技术最终汇聚到了一起.可见现在技术发展的趋势. JBoss的EJB3实现中,就使用Hibernate EntityManager 和Annotations 作为数据持久化机制,本文不准备讨论如何在JBoss中使用Hibernate EntityManager 我们在本文中看看如何在JSE环境中使用EntityManger, 这样当你的项目需要扩展到JEE容器中时,同样的EntityManger升级是很简单的. OK,下面我们看看如何在JSE环境中应用EntityManager吧: 环境配置: JDK : v5.0 or 更新 Hibernate core : v3.1.1 or 更新(要包涵Hibernate Core所需要的Jar库) Hibernate Annotation: v3.1beta8 Hibernate EntityManger: v3.1beta6 下面看两个相关的定义 EntityManagerFactory EntityManagerFactory 提供 Entity manager的实例(instances:所有被配置的实例都连接相同的数据库)利用相同的默认设置.你可以准备几个EntityManagerFactory 来访问不同的数据库.该接口(interface)和Hibernate core中的SessionFactory差不多.  EntityManager EntityManager API 是用来在一个特别的工作单元(particular unit of work)中访问数据库的.她用来创建和删除(create and remove) 持久实体实例的;可以通过实体的主键标识符(primary key identity)来查询(find)实体;或者查询所有实体. 这个接口和Hibernate core中的Session差不多. 因此,使用Hibernate EntityManager 和使用Hibernate Core 是差不多的,只不过 EntityManger还可以方便的在JEE容器中使用,这就是EJB3 的持久化实现机制. 下面我通过一个来自EntityManger test suit中的修改版的简单示例来演示一些如何在JSE环境中配置和操作持久化实体. 下面是一个利用Hibernate Annotation注释的持久化实体: /*  * Created on 2006-2-5  * @author icerain  */ package test.test; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityResult; import javax.persistence.FieldResult; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.SqlResultSetMapping; @Entity(name = "Item") //    @SqlResultSetMapping(name = "getItem", entities = //    @EntityResult(name = "org.hibernate.ejb.test.Item", fields = { //    @FieldResult(name = "name", column = "itemname"), //    @FieldResult(name = "descr", column = "itemdescription") //    }) //) //@Cache(region="Item", usage=NONSTRICT_READ_WRITE) public class Item implements Serializable {   private String name;   private String descr;   //private Set<Distributor> distributors;   public Item() {   }   public Item(String name, String desc) {     this.name = name;     this.descr = desc;   }   @Column(length = 200)   public String getDescr() {     return descr;   }   public void setDescr(String desc) {     this.descr = desc;   }   @Id   @Column(length = 30)   public String getName() {     return name;   }   public void setName(String name) {     this.name = name;   } //  @OneToMany //  public Set<Distributor> getDistributors() { //    return distributors; //  } // //  public void setDistributors(Set<Distributor> distributors) { //    this.distributors = distributors; //  } // //  public void addDistributor(Distributor d) { //    if ( distributors == null ) distributors = new HashSet(); //    distributors.add( d ); //  } } 下面是测试和配置的代码: /*  * Created on 2006-2-5  * @author icerain  */ package test.test; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Map; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.hibernate.cfg.Environment; import org.hibernate.ejb.Ejb3Configuration; import org.hibernate.ejb.HibernatePersistence; public class TestConfig {   private EntityManagerFactory emf = null;   public TestConfig() {     this(null);   }   public TestConfig(String fileName) {     // 利用Ejb3Configuration来建立EntityManagerFactory      emf = new Ejb3Configuration().addAnnotatedClass(Item.class).createEntityManagerFactory();  //(1) 看下面解释     //emf = Persistence.createEntityManagerFactory("manager1"); // 在JSE环境中不可以使用??? (2) 看下面解释     System.out.println("Create EMF:::::");   // 利用HibernatePersistence来建立EntityManagerFactory      //emf = new HibernatePersistence().createEntityManagerFactory(getConfig());  //(3) 看下面解释   }      public  Properties loadProperties() {     Properties props = new Properties();     InputStream stream = Persistence.class.getResourceAsStream( "/hibernate.properties" );     if ( stream != null ) {       try {         props.load( stream );       }       catch (Exception e) {         throw new RuntimeException( "could not load hibernate.properties" );       }       finally {         try {           stream.close();         }         catch (IOException ioe) {         }       }     }     props.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );     return props;   }   private Map getConfig() {     Map config = loadProperties();     ArrayList<Class> classes = new ArrayList<Class>();     classes.add(Item.class);     config.put( HibernatePersistence.LOADED_CLASSES, classes );          return config;   }      public void testEntityManager() { // 测试持久化数据操作 (4)     Item item = new Item( "Mouse1", "Micro$oft mouse" );     EntityManager em = emf.createEntityManager();     em.getTransaction().begin();     em.persist( item );     System.out.println( em.contains( item ) );     em.getTransaction().commit();     System.out.println(em.contains(item));     em.getTransaction().begin();     item = (Item) em.createQuery( "from Item where descr like 'M%'" ).getSingleResult();          System.out.println(item.getDescr() + ":" + item.getName());          item.setDescr( "Micro$oft wireless mouse" );     em.getTransaction().commit();          System.out.println(item.getDescr() + ":" + item.getName());     em.close();     closeEMF();   }      public void closeEMF() {     emf.close();     System.out.println("EMF is closed..");   }   /**    * @param args    */   public static void main(String[] args) {     // TODO Auto-generated method stub     new TestConfig().testEntityManager();   } } 上面就是测试代码,可以看到,我们可以用不同的方法来创建 EntityManagerFactory , 之所以有这么多方法是为了在不同的环境中使用的. (1): 利用Ejb3Configuration来建立EntityManagerFactory ,她会在工程目录下寻找hibernate.properties 配置文件(hibernate.cfg.xml好像不可以,大家可以试试看),然后根据配置信息来创建EntityManagerFactory . 配置文件如下: #Created by JInto - www.guh-software.de #Sun Feb 05 22:38:30 CST 2006 hibernate.cache.provider_class=org.hibernate.cache.HashtableCacheProvider hibernate.cache.region_prefix=hibernate.test hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.password=329 hibernate.connection.pool_size=1 hibernate.connection.url=jdbc\:mysql\://localhost/test3 hibernate.connection.username=root hibernate.default_batch_fetch_size=8 hibernate.dialect=org.hibernate.dialect.MySQLDialect hibernate.hbm2ddl.auto=update hibernate.jdbc.batch_versioned_data=true hibernate.jdbc.use_streams_for_binary=true hibernate.max_fetch_depth=1 hibernate.order_updates=true hibernate.proxool.pool_alias=pool1 hibernate.query.substitutions=true 1, false 0, yes 'Y', no 'N' javax.persistence.provider=org.hibernate.ejb.HibernatePersistence (2)文档上说利用Persistence可以创建的 但是我利用不同方法试了几下,都不可以,大家可以试试 如果你知道如何用 要记得告诉我哦 :). (3) 利用HibernatePersistence来建立EntityManagerFactory, 她可以利用一个properties 来创建, 该properties 你可以随便创建 只有包含必要的配置信息就可以了, 上面的代码中用了一个Map . (4):  调用testEntityManager() 方法 测试持久化数据操作 . ok, 到此一个简单的在JSE环境中使用EntityManger的介绍就结束了. 后记:   在JSE环境中使用 Hibernate Core 和EntityManager 是差不多的, 有没有必要使用EntityManager,个人认为 使用EntityManager就是为了应付将来项目扩展的JEE容器中使用,这样持久化部分实现很容易在JEE容器中实现,只要利用JNDI得到EntityManagerFactory就可以了,别的就没有什么改动了.如果你的项目不在JEE中使用的话, 没有必要用EntityManager.


阅读全文(2796) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.809 second(s), page refreshed 144819227 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号