Hibernate/JPA-EntityNotFoundException:无法找到id为的
我有一个场景,其中两个实体具有@manytone关系。该应用程序同时使用Spring数据jpa和Hibernate。我试图通过SpringDataJPA repo的save()方法保存子实体,另一个通过hibernate的getSession().save()保存。其结尾为实体未找到异常。在第一次保存之后,它不会在DB中插入记录,因为随后的保存会失败。寻找一个解决方案,使其工作 样本代码:Hibernate/JPA-EntityNotFoundException:无法找到id为的,hibernate,jpa,Hibernate,Jpa,我有一个场景,其中两个实体具有@manytone关系。该应用程序同时使用Spring数据jpa和Hibernate。我试图通过SpringDataJPA repo的save()方法保存子实体,另一个通过hibernate的getSession().save()保存。其结尾为实体未找到异常。在第一次保存之后,它不会在DB中插入记录,因为随后的保存会失败。寻找一个解决方案,使其工作 样本代码: EntityA a = new EntityA(); entityADao.save(); //Not
EntityA a = new EntityA();
entityADao.save(); //Not inserting the record
EntityB b = new EntityB();
b.setEntityA(a);
b.save(); //Throwing entityA not found exception.
测试等级:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-application-context-dao.xml" })
@Transactional(propagation= Propagation.REQUIRES_NEW)
public class EntityTest{
@Autowired
private EntityADao entityADao;
private EntityBDao entityBDao;
@Autowired
private SessionFactory sessionFactory;
@PostConstruct
public void orderDaoTest()
{
subject = new EntityBDaoImpl (sessionFactory);
System.setProperty("SERVER_TYPE", "junit"); // need to do this
}
@Test
public void testListByEntityB()
{
EntityA a = new EntityA();
a.setId("123");
entityADao.save(); //Not inserting the record
EntityB b = new EntityB();
b.setEntityA(a);
b.save(); //Throwing entityA not found exception with id "123".
List<EntityB> bList = entityBDao.listById(a.getId());
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(位置={“classpath:test application context dao.xml”})
@事务性(传播=传播。需要\u新建)
公共类实体测试{
@自动连线
私人实体(大)大(大)大(大);;
私人机构;私人机构;私人机构;
@自动连线
私人会话工厂会话工厂;
@施工后
public void orderDaoTest()
{
主题=新实体bdaoimpl(会话工厂);
System.setProperty(“服务器类型”、“junit”);//需要这样做
}
@试验
公共void testListByEntityB()
{
EntityA=新的EntityA();
a、 setId(“123”);
entityADao.save();//不插入记录
EntityB=新的EntityB();
b、 setEntityA(a);
b、 save();//引发id为“123”的未找到实体异常。
List bList=entityBDao.listById(a.getId());
}
}
谢谢,
Preethi您可以发布包含上述保存逻辑的类吗。这是在事务中调用的吗?我感觉代码中有错误。您正在创建
EntityA a
并调用不带参数的entityADao.save()
。但是,您要将新创建的EntityA a
保存到哪里,甚至对于EntityB
您也要创建它并对其调用save()
方法。它是在内部调用session.save/persist,还是应该改为entityBDao.save(b)
?