gpt4 book ai didi

java - org.hibernate.TransientObjectException : how to properly define one-to-one relationship?

转载 作者:太空宇宙 更新时间:2023-11-04 11:40:04 24 4
gpt4 key购买 nike

保存复合对象时,我不断收到此异常。仍然不知道如何克服它。这是我的映射:

@Entity
@Table(name = "store_house")
public class StoreHouse implements Serializable {

// constructors

@Id
@OneToOne(fetch = FetchType.EAGER)
@Cascade({org.hibernate.annotations.CascadeType.ALL})
@JoinColumn(name="ING_ID", unique=true, nullable=false, updatable=false)
private Ingredient ingredient;

@Column(name = "QUANTITY")
private double quantity;
}

// getters and setters

这是 DAO 方法,我在其中遇到此异常:

    @Override
public void insert(StoreHouse sh) {
sessionFactory.getCurrentSession().persist(sh);
}

这是我的测试类(class):

@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/test-context.xml", "/test-data.xml"})
public class StoreHouseDAOTest {

@Autowired
private SessionFactory sessionFactory;

@Autowired
private StoreHouseDAO storeHouseDAO;

@Autowired
private StoreHouse expectedStoreHouse;

@Test
public void itShouldPerformCRUDSmoothly() {
// CREATE
storeHouseDAO.insert(expectedStoreHouse);
sessionFactory.getCurrentSession().flush();
// READ
StoreHouse actualStoreHouse = storeHouseDAO.getByIngredient(expectedStoreHouse.getIngredient());
assertEquals(actualStoreHouse.getIngredient().getId(), expectedStoreHouse.getIngredient().getId());
// DELETE
storeHouseDAO.delete(expectedStoreHouse);
sessionFactory.getCurrentSession().flush();
StoreHouse emptyStoreHouse = storeHouseDAO.getByIngredient(expectedStoreHouse.getIngredient());
assertNull(emptyStoreHouse);
}
}

定义的测试数据片段:

   <bean id="expectedIngredient" class="com.restaurant.model.Ingredient">
<property name="name" value="TestIngredient"/>
<property name="unit" value="expectedUnit"/>
</bean>

<bean id="expectedStoreHouse" class="com.restaurant.model.StoreHouse">
<property name="ingredient" ref="expectedIngredient"/>
<property name="quantity" value="10"/>
</bean>

我觉得我在这里定义级联时搞砸了..但是你能帮我改正它吗?

最佳答案

我设法让它发挥作用,但代价是简化模型。

@Entity
@Table(name = "store_house")
public class StoreHouse implements Serializable {

// constructors

@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "SH_ID")
private Long id;

@OneToOne(fetch = FetchType.EAGER)
@Cascade({org.hibernate.annotations.CascadeType.ALL})
@JoinColumn(name="ING_ID", unique=true, nullable=false, updatable=false)
private Ingredient ingredient;

@Column(name = "QUANTITY")
private double quantity;

// getters and setters
}

它实际上需要一个单独的 id 字段,所以我创建了它。并表示工作顺利。可能会选择它,因为没有找到其他解决方案。

关于java - org.hibernate.TransientObjectException : how to properly define one-to-one relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42901218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com