JBoss的EJB
環境配置:
JDK : v
Hibernate core : v
Hibernate Annotation: v
Hibernate EntityManger: v
下面看兩個相關的定義
EntityManagerFactory
EntityManagerFactory 提供 Entity manager的實例(instances:所有被配置的實例都連接相同的數據庫)利用相同的默認設置
EntityManager
EntityManager API 是用來在一個特別的工作單元(particular unit of work)中訪問數據庫的
因此
下面我通過一個來自EntityManger test suit中的修改版的簡單示例來演示一些如何在JSE環境中配置和操作持久化實體
下面是一個利用Hibernate Annotation注釋的持久化實體:
/*
* Created on
* @author icerain
*/
package test
import java
import java
import java
import javax
import javax
import javax
import javax
import javax
import javax
import javax
@Entity(name =
// @SqlResultSetMapping(name =
// @EntityResult(name =
// @FieldResult(name =
// @FieldResult(name =
// })
//)
//@Cache(region=
public class Item implements Serializable {
private String name;
private String descr;
//private Set
public Item() {
}
public Item(String name
this
this
}
@Column(length =
public String getDescr() {
return descr;
}
public void setDescr(String desc) {
this
}
@Id
@Column(length =
public String getName() {
return name;
}
public void setName(String name) {
this
}
// @OneToMany
// public Set
// return distributors;
// }
//
// public void setDistributors(Set
// this
// }
//
// public void addDistributor(Distributor d) {
// if ( distributors == null ) distributors = new HashSet();
// distributors
// }
}
下面是測試和配置的代碼:
/*
* Created on
* @author icerain
*/
package test
import java
import java
import java
import java
import java
import javax
import javax
import javax
import org
import org
import org
public class TestConfig {
private EntityManagerFactory emf = null;
public TestConfig() {
this(null);
}
public TestConfig(String fileName) {
// 利用Ejb
emf = new Ejb
//emf = Persistence
System
// 利用HibernatePersistence來建立EntityManagerFactory
//emf = new HibernatePersistence()
}
public Properties loadProperties() {
Properties props = new Properties();
InputStream stream = Persistence
if ( stream != null ) {
try {
props
}
catch (Exception e) {
throw new RuntimeException(
}
finally {
try {
stream
}
catch (IOException ioe) {
}
}
}
props
return props;
}
private Map getConfig() {
Map config = loadProperties();
ArrayList
classes
config
return config;
}
public void testEntityManager() { // 測試持久化數據操作 (
Item item = new Item(
EntityManager em = emf
em
em
System
em
System
em
item = (Item) em
System
item
em
System
em
closeEMF();
}
public void closeEMF() {
emf
System
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto
new TestConfig()
}
}
上面就是測試代碼
(
配置文件如下:
#Created by JInto
#Sun Feb
hibernate
hibernate
nnection
nnection
nnection
nnection
nnection
hibernate
hibernate
hibernate
hibernate
hibernate
hibernate
hibernate
hibernate
hibernate
javax
(
(
(
ok
後記:
在JSE環境中使用 Hibernate Core 和EntityManager 是差不多的
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28309.html