Reputation: 2071
In JPA/Hibernate, is it possible to express a foreign key without adding a relationship?
In DDD in aggregate root I would like to have an id of other aggregate root - I don't want to have a reference to this aggregate, only id. Is it possible to enforce foreign key by hibernate? (I use hibernate auto schema generation).
EG
@Entity
Person {
...
}
@Entity
Event {
@Id
private long eventId;
@ForeignKey(references Person.id)
private long personId;
// I don't want to map it as @ManyToOne Person
}
I don't want to use @ManyToOne, because I don't want to store a reference to other aggregate in Event aggregate. It would be DDD antipattern.
Upvotes: 3
Views: 1080
Reputation: 2948
You can use the columnDefinition
in @Column
to add the constraint.
@Column(columnDefintion="bigint references Person(id)")
private long personId;
Note that you would need to use database specific SQL type and syntax for the constraint.
Upvotes: 3
Reputation: 13041
You can try to use importing script file.
4.1. Importing script files
To customize the schema generation process, the
hibernate.hbm2ddl.import_files
configuration property must be used to provide other scripts files that Hibernate can use when theSessionFactory
is started.
<property name="hibernate.hbm2ddl.import_files" value="schema-generation.sql" />
Hibernate is going to execute the script file after the schema is automatically generated.
Upvotes: 1