Home > OS >  hibernate ORM search an entity using oneToMany List of objects
hibernate ORM search an entity using oneToMany List of objects

Time:01-31

I have the following entities.

@Entity
public class Blog{
  @Id
  Long id;
  @Column
  String name;
  @Column
  String datePosted;
  @OneToOne(orphanRemoval=true,cascade=CascadeType.ALL)
  Metadata metadata;
}

@Entity
public class Metadata{
    @Id
    Long id;
    OneToMany(orphanRemoval=true,cascade=CascadeType.ALL)
    List<Category> categories;
}

@Entity
public class Category{
    @Id
    Long id;
    @Column
    String name;
    @Column
    Sting type;
}

Now I have list of Categories so like this:

List<Category> categories;

Assume that the above list contains values; I want to search Blog using categories. Could you help me how to go about that?

CodePudding user response:

Based on my understanding, you will firstly need to fix your connections. To begin with, you will have to add this to the class Blog (metadata_id should be replaced with the name of the respective database field):

 @OneToOne(cascade = CascadeType.ALL)
 @JoinColumn(name = "metadata_id", referencedColumnName = "id")
 Metadata metadata;

Also, you will need this statement to the class Metadata:

 @OneToOne(mappedBy = "metadata")
 private Blog blog;

Now that you have a correct one to one connection between Blog and Metadata (Blog has a foreign key of the Metadata PK), you will have to create a many-to-one and one-to-many connection between the classes: Metadata and Category.

Based on my understanding, one Metadata has a lot of Categories, so you should add this to the class Metadata:

 @OneToMany(mappedBy="metadataFK")
 List<Category> categories;

Also you will have to add this to the class Category:

 @ManyToOne
 @JoinColumn(name="metadata_id")
 private Metadata metadataFK;

After you do all these you should be fine. I am not entirely sure about your question, but I suspect that you will have to use SQL (or HQL) to access Blogs through the Categories.

CodePudding user response:

I am trying to do the following:

private static List fingByCategory(List categories) { Session session = getSessionFactory().openSession();

    String hql = "from Blog b join fetch b.metadata.categories c where c in     :categories";       
Query query = session.createQuery(hql, Blog.class);
     query.setParameter("categories", categories);
    List<Blog> blogs = query.getResultList();
    session.close();
    return blogs;
}

But getting error: java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance beforeQuery flushing: test.hb.Category

All the oneToOn and ManyToOne or oneToMany relationships are marked as (cascade = CascadeType.ALL) Could you help me what I am doing wrong?

  •  Tags:  
  • Related