简体   繁体   中英

JPQL many to many select query

I have two entity class and repository looks like following. I`m making jpql select query.

Subscription.java

@Entity
@Table(name="Subscription")
public class Subscription implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="SubscriptionId", nullable=false)
    private Integer subscriptionId;

    @Column(name="BaseProductId", nullable=false)
    private Integer baseProductId;

    @ManyToMany(fetch = FetchType.LAZY, mappedBy="subscription")
    private List<Abc> abc;
}

Abc.java

@Entity
@Table(name="abc")
public class Abc implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="SubscriptionId", nullable=false)
    private Integer id;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinColumn(name="id", referencedColumnName="BaseProductId", insertable = false, updatable = false, nullable = false)
    private List<Subscription> subscription;
}

AbcRepository.java

@Repository
public interface AbcRepository extends JpaRepository<Abc, Integer> {

    @Query(value="SELECT bpp FROM Abc bpp JOIN bpp.subscription s WHERE s.subscriptionId = ?1")
        public List<Abc> findBppm(Integer a);
    }
}

Select query generating:

select ... from abc bp_ inner join abc_subscription ... inner join Subscription subscripti2_ on ... where subscripti2_.SubscriptionId=?

... :- it have something at this place.

Though i`m joining abc and subscription, but in query hibernate creating one more entity separated by _. ie abc_subscription.

Any idea what i`m doing wrong? Thanks in advance.

@ManyToMany should be used in scenarios where there is a link table between entities.

If @JoinTable is not specified, the default link table used by the persistence provider would be the the concatenation of both entities separated by a "_". On top of that, f not specified the assumed column names in the link table would be the @Id field names as defined on the entity classes.

Try to follow the spec and adapt your situation accordingly: ManyToMany javadoc

As a rule, avoid using Lists for Many to many relationships because this can cause problems when deleting a field from either of the entities. Instead use Sets private Set<> abc = new HashSet<>();

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