这是一个简单的程序,用于写入和读取 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();
}
}
提前致谢。