这是一个简单的程序编写,并从一个MySQL数据库中读取。 当我输入测试数据,这一切是在MySQL客户端可见。 然而,当我使用OpenJPA的检索相同的数据,所有的ID显示为“0”,但名称是正确的。 可能是什么原因在交易过程中迷路的ID?
POJO类
import java.io.Serializable;
import javax.persistence.*;
@Entity (name="People")
public class People implements Serializable{
/**
*
*/
private static final long serialVersionUID = 801578124126646759L;
@Id
private int id;
@Column(length=32)
private String name;
public People(int id,String name)
{
setId(id);
setName(name);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
类从数据库中读取
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class PeopleGetter {
EntityManager entityManager;
public PeopleGetter(EntityManager entityManager)
{
this.entityManager=entityManager;
}
@SuppressWarnings("unchecked")
public List<People> getAllPeople()
{
Query query=entityManager.createQuery("SELECT x FROM People x");
return query.getResultList();
}
}
类打印数据
import java.io.PrintStream;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class PeoplePrinter {
private PeopleGetter peopleGetter;
private PrintStream out = System.out;
public PeoplePrinter(PeopleGetter peopleGetter)
{
this.peopleGetter=peopleGetter;
}
public void setPrintStream (PrintStream stream){
out = stream;
}
public void getAllPeopleAndPrint()
{
List<People>peopleList=peopleGetter.getAllPeople();
for(People person: peopleList) {
out.println(person.getId()+"=>"+person.getName());
}
}
}
主要测试类
import javax.persistence.*;
public class MainClass {
public static void generateNames()
{
EntityManager entityManager = getEntityManager();
EntityTransaction userTransaction = entityManager.getTransaction();
userTransaction.begin();
entityManager.persist(new People(1,"Ali"));
userTransaction.commit();
userTransaction.begin();
entityManager.persist(new People(2,"Veli"));
userTransaction.commit();
userTransaction.begin();
entityManager.persist(new People(3,"Ahmet"));
userTransaction.commit();
userTransaction.begin();
entityManager.persist(new People(4,"Mehmet"));
userTransaction.commit();
entityManager.close();
}
public static EntityManager getEntityManager()
{
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("openjpa");
EntityManager entityManager = entityManagerFactory.createEntityManager();
return entityManager;
}
public static void resetTable()
{
EntityManager em = getEntityManager();
Query query = em.createQuery("DELETE FROM People x");
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
query.executeUpdate();
userTransaction.commit();
em.close();
}
public static void main(String[] args)
{
resetTable();
generateNames();
EntityManager em = getEntityManager();
PeoplePrinter peoplePrinter=new PeoplePrinter(new PeopleGetter(em));
peoplePrinter.getAllPeopleAndPrint();
em.close();
}
}
提前致谢。