@OneToOne relation mappedBy @Any?

Perhaps a strange modelling question: I would like to define a OneToOne relation mapped by an Any relation. I’m modelling CRUD Actions, where Creation and Update each have one Stuff attached, but Read has many Stuffs. This means I can’t just put the foreign keys in the Action tables. What I had in mind would look like this:

@Entity
public class ActionCreate extends Action {
	@OneToOne(mappedBy = "action")
	private Stuff stuff;
}

// ActionUpdate like ActionCreate

@Entity
public class ActionRead extends Action {
	@OneToMany(mappedBy = "action")
	private Set<Stuff> stuffs = new HashSet<Stuff>();
}

@Entity
public class Stuff {
	@Any
	@AnyDiscriminator(DiscriminatorType.STRING)
	@AnyDiscriminatorValue(discriminator = "ActionCreate",entity = ActionCreate.class)
	@AnyDiscriminatorValue(discriminator = "ActionRead", entity = ActionRead.class)
	@AnyDiscriminatorValue(discriminator = "ActionUpdate", entity = ActionUpdate.class)
	@AnyKeyJavaClass(Long.class)
	@Column(name = "action_type")
	@JoinColumn(name = "action_id")
	private Action action;
}

Hibernate doesn’t support this at the moment, but should it? I mean, is that a reasonable feature? OneToMany mapped by Any is supported now (thanks for that by the way :grin:), but I have no idea if implementing this would be at all similar.

Either way, for the time being it seems that I need something like Mapping unidirectional one-to-one relations correctly, I’ll also ask there.

I don’t think that @Any is the “right” target for a @OneToOne(mappedBy = "..."), because it has no unique constraint on (action_type, action_id). You can’t map that constraint though, since you use the Stuff#action relationship also for your @OneToMany, so in your particular use case, this would IMO not make sense or be unsafe.

You could map it differently though, if you don’t care about safety:

@Entity
public class ActionCreate extends Action {
	@MapsId
	@OneToOne
	@JoinColumn(name = "id", referencedColumnName = "action_id")
	private Stuff stuff;
}

I would stick to mapping it with an explicit FK join column though:

@Entity
public class ActionCreate extends Action {
	@OneToOne
	@JoinColumn(name = "stuff_id")
	private Stuff stuff;
}

I had started a discussion on the subject on Zulip:

(29001) #hibernate-user > @OneToOne(mappedby) with a @Any KO - Hibernate - Zulip