Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jpa/Hibernate map foreign key without relationship

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.

like image 989
bastiat Avatar asked Dec 09 '25 08:12

bastiat


2 Answers

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.

like image 152
areus Avatar answered Dec 11 '25 11:12

areus


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 the SessionFactory 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.

like image 44
SternK Avatar answered Dec 11 '25 11:12

SternK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!