org.hibernate.TransientObjectException:如何正确定义一对一关系?

时间:2017-03-20 10:28:48

标签: java spring hibernate one-to-one cascading

保存复合对象时,我一直收到此异常。仍然无法想象如何克服它.. 这是我的映射:

@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);
    }

这是我的测试记录:

@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>

我觉得在这里定义Cascading时我很笨拙..但你能帮我纠正吗?

1 个答案:

答案 0 :(得分:0)

我设法以简化模型为代价使其工作。

@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字段,所以我创建了它。它被认为可以顺利运作。可能会继续使用它,因为没有找到其他解决方案。