문제

I have a many-to-many table that looks somewhat like this. It's accessed through ormlite and stored in an embedded h2 database.

@DatabaseField(id = true)
private String id;

@DatabaseField(foreign = true, canBeNull = false, uniqueCombo = true, foreignAutoRefresh = true)
private ForeignOne foreignOne;

@DatabaseField(foreign = true, canBeNull = false, uniqueCombo = true, foreignAutoRefresh = true)
private ForeignTwo foreignTwo;

If I try to store an instance in which one or both of the foreign members are null the DAO object throws an exception as expected as the annotation states canBeNull = false.

However if one or both of the foreign members are set to instances that do not exist in the database I am able to perform the insertion into the database and the next time I retrieve the instance from the database those foreign members that did not exist on insertion are null.

Is there any way to avoid this?

Thanks

도움이 되었습니까?

해결책

A not null constraint merely means the field cannot be null, it does not mean it has to be a valid key. If you want to ensure that your foreign key actually points to a row in the foreign table, you need to create a foreign key constraint, which is not fully supported in ORMLite. Instead you have to use a custom column definition, something like

@DatabaseField(foreign = true,
               columnDefinition = "integer references foreignOne(id)" )
private ForeignOne foreignOne;

to get ORMLite to create one. Or you can create the h2 database yourself and include one.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top