Home > Software design >  @OneToMany field is wrongly included in JPA query
@OneToMany field is wrongly included in JPA query

Time:07-11

I have a small project to tinker with Spring, where I have two entities with a one to many association: 1 Restaurant -> N Dishes. I have the following PostgreSQL schema for that:

create table if not exists restaurants (
    restaurant_id uuid primary key,
    name varchar(512) not null,
    description varchar(1024) not null,
    address varchar(512) not null,
    photo_url varchar(1024)
);

create table if not exists dishes (
    dish_id uuid primary key,
    name varchar(512) not null,
    description varchar(1024),
    photo_url varchar(1024),
    restaurant_id uuid references restaurants(restaurant_id) not null,
    price int not null check (price > 0)
);

With the following JPA Entities:

@Entity
@Table(name = "restaurants")
class Restaurants(
    @Id
    var restaurantId: UUID,
    var name: String,
    var description: String,
    var photoUrl: String?,
) {
    @OneToMany(mappedBy = "restaurant")
    @JoinColumn(name = "restaurant_id", nullable = false)
    var dishes: MutableList<Dishes> = mutableListOf()
}
@Entity
@Table(name = "dishes")
class Dishes(
    @Id
    var dishId: UUID,
    var name: String,
    var description: String,
    var photoUrl: String?,
    var price: Int,
    @ManyToOne(optional = false)
    @JoinColumn(name = "restaurant_id", nullable = false)
    var restaurant: Restaurants
)

I have defined a RestaurantsRepository as follows:

interface RestaurantsRepository: R2dbcRepository<Restaurants, UUID> {
    fun findByRestaurantId(restaurantId: UUID): Mono<Restaurants>
}

The problem I'm having is that when I call findByRestaurantId I have the following exception:

org.springframework.r2dbc.BadSqlGrammarException: executeMany; bad SQL grammar [SELECT restaurants.restaurant_id, restaurants.name, restaurants.description, restaurants.photo_url, restaurants.dishes FROM restaurants WHERE restaurants.restaurant_id = $1]; nested exception is io.r2dbc.postgresql.ExceptionFactory$PostgresqlBadGrammarException: [42703] column restaurants.dishes does not exist
    at org.springframework.r2dbc.connection.ConnectionFactoryUtils.convertR2dbcException(ConnectionFactoryUtils.java:235) ~[spring-r2dbc-5.3.21.jar:5.3.21]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: 

Why is the @OneToMany field included in the SQL query?

CodePudding user response:

You are trying to use Spring Data R2DBC (R2dbcRepository) in conjunction with JPA annotations. It won't work: these are two different technologies. R2DBC does not support @ManyToOne nor @JoinColumn so the annotations are simply ignored.

  • Related