I tried to implement a reference table when it comes to ManyToMany relation in the context of DDD based on this article(https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates)
I have different naming for JdbcEntity because I have another Domain Entity named Book
which handles domain logic. (I've decided to decouple Domain model
and Persistence model
which is JdbcEntity
as below)
The problem is the class name BookJdbcEntity
is mapped as a foreign key name in book_author
automatically:
"PreparedStatementCallback; bad SQL grammar [SELECT `book_author`.`AUTHOR_ID` AS `AUTHOR_ID` FROM `book_author` WHERE `book_author`.`BOOK_JDBC_ENTITY` = ?]; nested exception is java.sql.SQLSyntaxErrorException: (conn=845) Unknown column 'book_author.BOOK_JDBC_ENTITY' in 'where clause'",
Is there any possible way to generate the below SQL statement? (book_id
instead of BOOK_JDBC_ENTITY
)
SELECT `book_author`.`AUTHOR_ID` AS `AUTHOR_ID` FROM `book_author` WHERE `book_author`.`book_id` = ?
Jdbc Entity:
@Table("book")
data class BookJdbcEntity(
@Id val id: Long,
val title: String,
val isbn: String,
val pages: Int,
val authors: Set<AuthorRef> = hashSetOf()
)
@Table("book_author")
data class AuthorRef(val authorId: Long)
Schema:
CREATE TABLE IF NOT EXISTS book
(
id bigint(20) NOT NULL,
title VARCHAR(100) NOT NULL,
isbn varchar(100) not null,
pages INTEGER not null,
PRIMARY KEY (id)
);
CREATE TABLE IF NOT EXISTS book_author
(
book_id bigint(20) NOT NULL,
author_id bigint(20) NOT NULL,
constraint book_id_fk foreign key (book_id) references book (id)
);
That's done with @MappedCollection
@Table("book")
data class BookJdbcEntity(
@Id val id: Long,
val title: String,
val isbn: String,
val pages: Int,
@MappedCollection(idColumn="book_id")
val authors: Set<AuthorRef> = hashSetOf()
)