Java JPA EntityManager不存在
我对JPA和将数据持久化到数据库中有问题。 我有以下课程Java JPA EntityManager不存在,java,mysql,jpa,Java,Mysql,Jpa,我对JPA和将数据持久化到数据库中有问题。 我有以下课程 public class Grabber { private EntityManagerFactory emfactory; private EntityManager entitymanager; public EntityManager getManager(){ emfactory = Persistence.createEntityManagerFactory( "DSLTes
public class Grabber {
private EntityManagerFactory emfactory;
private EntityManager entitymanager;
public EntityManager getManager(){
emfactory = Persistence.createEntityManagerFactory( "DSLTestV4" );
entitymanager = emfactory.
createEntityManager( );
entitymanager.getTransaction( ).begin( );
return entitymanager;
}
public void Close(){
entitymanager.getTransaction().commit();
entitymanager.close();
emfactory.close();
}
}
下面的wich扩展了抓取器
public class TestfixtureGrabber extends Grabber{
public List<Testfixture> getAll(){
EntityManager manager = getManager();
List<Testfixture> result = manager.createNamedQuery("Testfixture.findAll").getResultList();
Close();
return result;
}
public Testfixture getById(int id){
EntityManager manager = getManager();
TypedQuery<Testfixture> query = manager.createQuery("SELECT w FROM User w WHERE w.user=" +id ,Testfixture.class);
Testfixture result = query.getSingleResult();
Close();
return result;
}
@Transactional
public int SaveTestfixture(Testfixture t){
EntityManager em = getManager();
em.persist(t);
em.flush();
int id = t.getId();
em.close();
return id;
}
}
公共类TestfixtureGrabber扩展了Grabber{
公共列表getAll(){
EntityManager=getManager();
List result=manager.createNamedQuery(“Testfixture.findAll”).getResultList();
Close();
返回结果;
}
公共Testfixture getById(int-id){
EntityManager=getManager();
TypedQuery query=manager.createQuery(“从用户w中选择w,其中w.User=“+id,Testfixture.class”);
Testfixture结果=query.getSingleResult();
Close();
返回结果;
}
@交易的
公共int SaveTestfixture(Testfixture t){
EntityManager em=getManager();
em.t;
em.flush();
int id=t.getId();
em.close();
返回id;
}
}
获取操作工作得很好,当我保存实体时,它会获取一个ID,并以某种方式保存到本地上下文中。但是当我检查我的MySQL数据库时,它说这个表是一个空集。没有数据保存到数据库中
我尝试了各种方法,并尝试在persist之后添加flush(),但没有成功
为什么我不能让它工作?有什么想法吗?在SaveTestfixture(Testfixture t)
您不想使用em.close()代码>但关闭()代码>
另外,为什么在SaveTestfixture(Testfixture t)
您不想使用em.close()代码>但关闭()代码>
另外,为什么此方法带有@Transactional
注释,因此在提交事务之前关闭EntityManager?您没有提交事务。此外,EMF应该创建一次,而且只能创建一次。创建它是一项代价高昂的操作,需要读取所有元数据、注释等。您还应该遵守Java命名约定,使用try finally确保em始终关闭,等等。因此,您在提交事务之前关闭EntityManager?您没有提交事务。此外,EMF应该创建一次,而且只能创建一次。创建它是一个代价高昂的操作,需要读取所有元数据、注释等。您还应该遵守Java命名约定,使用try finally确保em始终关闭,等等。是的!当然,我不能告诉你我是怎么错过的!太棒了!:)这是注释,因为我几乎什么都试过了。甚至还做了一个祷告。。谢谢恐怖袋熊(Y):染料!当然,我不能告诉你我是怎么错过的!太棒了!:)这是注释,因为我几乎什么都试过了。甚至还做了一个祷告。。谢谢恐怖袋熊(Y):D