Neeraj N
Neeraj N

Reputation: 53

How to avoid extra table while joining the two columns in JPA?

I have two classes A & B with as :

This is the class A

class A{
  private int id;
  private String name ;
  private String emailId;
  
  @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy="aList")
  List<B> bList;
 
  // getter and setters 
}

This is the class B

class B{
  private int id;
  private int AId ;
  private String location;
  
  @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
  List<A> aList;
 
  // getter and setters 
}

And this is the Dao Class method with which I am trying to get the joined Data.

public List<A> getA() {
        Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession();
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<A> criteria = builder.createQuery(A.class);
        Root<A> root = criteria.from(A.class);
        Join<A, B> joinList = root.join("bList", JoinType.LEFT);
        try{
            Predicate filters = builder.and(builder.equal(joinList.get("AId"),root.get("id")),
                    builder.equal(root.get("name"), "xxx"));
            
            criteria.where(filters);
            List<A> aList = (List<A>)session.createQuery(criteria).getResultList();
            return aList;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

But every time it is creating another table and I don't want the extra table to be created rather I want to apply join like we do in mysql i.e without creating any extra table. How it can be done ??

Thanks

Upvotes: 0

Views: 224

Answers (1)

PTL
PTL

Reputation: 11

If I correctly understood you. JOIN operator is not creating new tables on its own. It is rather the way you described your entity. You have used Many to many relation which created another table. This table is needed to satisfy 3 Normal Form of database.

Solution

  1. Accept existence of another table, until you like to keep consistency of your DB, and prevent data leaks
  2. Redefine your entity so it has Many to one or One to many relation

Upvotes: 1

Related Questions