简体   繁体   中英

Spring data JPA - Exclude ID column from one entity parameter

I have two entities :

@Entity
public class Car {

    @Id
    private Long id;

    @OneToOne
    private Engine engine;
}

and the other one :

@Entity
public class Engine {

    @Id
    private Long id;

    @Column
    private String value1;

    @Column
    private String value2;
}

In my jpaRepositoy interface, i would like to do :

public interface CarRepository extends JpaRepository<Car, Long> {

    public Car findByEngine(Engine engine);
}

But this method doesn't return my entity stored, because I created my Engine doing :

Engine engine = new Engine("someValue", "someValue");

without setting engine's id which is stored in database.

So I would like to know if it is possible exclude a column like id ? If no, is the only way to do this is :

@Query("SELECT c FROM Car c WHERE c.engine.value1 = :value1 and c.engine.value2 = :value2")
findByEngine(@Param("value1") String value1, @Param("value2") String value2)

?

Related question : If I have OneToMany relationship instead of OneToOne, like

@Entity
public class Car {

    @Id
    private Long id;

    @OneToMany
    private List<Engine> engines;
}

How can I do this request to have something like (still without id column) :

public Car findByEngines(List<Engine> engines);

Thanks a lot !

This @Query("SELECT c FROM Car c WHERE c.value1 = :value1 and c.value2 = :value2") is not correct jpql query for your scenario, You do not have value1 and value2 in Car entity.

Correct one would be:

@Query("SELECT c FROM Car c WHERE c.engine.value1 = :value1 and c.engine.value2 = :value2").

You can try this method Name, I think that will work:

findByEngineValue1AndEngineValue2(String value1, String value2)

but for list one, i do not think you can make it up with just method name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM