一、
1、数据库的创建
createDB.java
import java.util.*;
import javax.persistence.*;
public class createDB {
public static void main(String[] args) {
// Open a database connection
// (create a new database if it doesn't exist yet):
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("$objectdb/db/points.odb");
EntityManager em = emf.createEntityManager();
// Store 1000 Point objects in the database:
em.getTransaction().begin();
for (int i = 0; i < 1000; i++) {
Point p = new Point(i, i);
em.persist(p);
}
em.getTransaction().commit();
// Close the database connection:
em.close();
emf.close();
}
}
Point.java
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Point implements Serializable {
private static final long serialVersionUID = 1L;
// Persistent Fields:
@Id
@GeneratedValue
Long id;
// private Boolean capital;
// private Long population;
// private String name;
private int x;
private int y;
// Constructors:
public Point(int x,int y) {
this.x = x;
this.y = y;
}
}
如果数据库应用在web应用中,$objectdb指objectdb.jar所在目录的上层文件夹,即WEB-INF
二、for tomcat &opm
1、
PointListener.java
package test;
import javax.persistence.*;
import javax.servlet.*;
public class PointListener implements ServletContextListener{
// Prepare the EntityManagerFactory & Enhance:
public void contextInitialized(ServletContextEvent e) {
//entityClass package name
com.objectdb.Enhancer.enhance("test.*");//com.objectdb.o.UserException:Package test1 is not found by the enhancer
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("$objectdb/db/points.odb");
e.getServletContext().setAttribute("emf", emf);
}
// Release the EntityManagerFactory:
public void contextDestroyed(ServletContextEvent e) {
EntityManagerFactory emf =
(EntityManagerFactory)e.getServletContext().getAttribute("emf");
emf.close();
}
}
2、web.xml
<listener>
<listener-class>test.PointListener</listener-class>
</listener>
四、错误
1、Persistence unit '$objectdb/lib/sqljdbc4.jar' is not found (by sun.misc.Launcher$AppClassLoader)
数据库名如果非*.odb,则应加上objectdb:$objectdb