0

I need to get Entity1's by entity2's ids

There is params for query - List numbers - ids of entity2 . And two entities with @OneToMany bound

@Entity
class Entity1 {
private Integer id;

private Entity2 entity2;

---------
@OneToMany(cascade = ALL, fetch =FetchType.EAGER)
@Column
public Entity2 getEntity2(){
return entity2;

}

and

@Entity
public class Entity2{

private Integer id;

@ManyToOne(FetchType.LAZY)
private Entity1 entity1;
}

i have working code

@Repository
public interface Entity1Repository extends JpaRepository<Entity1, Integer> {

@Query("SELECT c" +
            " FROM  Entity1 c" +
            " inner JOIN  c.entity2 a" +
            "  WHERE  a.id IN(?1)")
    Set<Entity1> findByEntity2Ids(List<Integer> pEntity2_Ids);
}

i want beautify query by using Spring Data

and write something like

Set<Entity1> findAllByEntity2In(List<Integer> pChannels);

but it doesnt work now

I catch an Enxception :

\Caused by: java.lang.IllegalArgumentException: Parameter value element [2] did not match expected type [com.test.Entity2 (n/a)]

Who knows how to solve?

Thanks !

3 Answers 3

1

UPD

I found out the query for Spring Data :

  @Repository
    public interface Entity1Repository extends JpaRepository<Entity1, Integer> {
 
    Set<Enity1> findByEntity2In(List<Integer> pEntities2Ids);

}
Sign up to request clarification or add additional context in comments.

Comments

0

Remove the brackets from the query. It should look like this:

@Query("SELECT c" +
            " FROM  Entity1 c" +
            " inner JOIN  c.entity2 a" +
            "  WHERE  a.id IN ?1")

For a better readable query, you could choose to use a named parameter instead of a positional one. Said so, your query could be like this:

@Query("SELECT c" +
            " FROM  Entity1 c" +
            " inner JOIN  c.entity2 a" +
            "  WHERE  a.id IN :ids")
    Set<Entity1> findByEntity2Ids(@Param("ids") List<Integer> pEntity2_Ids);

Comments

0

You can do search by List or set of Entity2 like

Set<Entity1> findByEntity2In(Set<Entity2> entity2);

For finding by Entity2 Id, you need to write Query like

@Query("SELECT ent1 FROM  Entity1 ent1 INNER JOIN  c.entity2 ent2 WHERE  ent2.id IN :ids")
Set<Entity1> findByEntity2Ids(@Param("ids") List<Integer> pEntity2_Ids);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.