package com.tch.test.openjpa;
import java.io.Serializable;
import javax.persistence.*;
@Entity
public class Point implements Serializable {
private static final long serialVersionUID = 1L;
@Id @GeneratedValue
private long id;
private int x;
private int y;
public Point() {
}
Point(int x, int y) {
this.x = x;
this.y = y;
}
public Long getId() {
return id;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public String toString() {
return String.format("(%d, %d)", this.x, this.y);
}
}
测试:
package com.tch.test.openjpa;
import javax.persistence.*;
import java.util.*;
public class Main {
private static EntityManager em;
private static EntityManagerFactory emf;
static {
// Open a database connection
emf = Persistence.createEntityManagerFactory("openjpa");
em = emf.createEntityManager();
}
public static void main(String[] args) {
try{
batchSave();
getCount();
typedQuery();
clearTable();
}catch(Exception e){
e.printStackTrace();
}finally{
// Close the database connection:
em.close();
emf.close();
}
}
private static void clearTable() {
em.getTransaction().begin();
em.createQuery("delete from Point").executeUpdate();
em.getTransaction().commit();
}
private static void typedQuery(){
// Retrieve all the Point objects from the database:
TypedQuery<Point> query =
em.createQuery("SELECT p FROM Point p", Point.class);
List<Point> results = query.setMaxResults(10).getResultList();
System.out.println(results.size());
}
private static void batchSave(){
long startTime = System.currentTimeMillis();
// 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();
System.out.println((System.currentTimeMillis()-startTime)+"ms");
}
private static void getCount(){
// Find the number of Point objects in the database:
Query q1 = em.createQuery("SELECT COUNT(p) FROM Point p");
System.out.println("Total Points: " + q1.getSingleResult());
}