0

I use hibernate. There are entries in the database (category), I display these categories on the page, without outputting their id only names. After I create the product, this product should have a connection with the derived categories (with one of them). And I have a question at this point. How can I save an object by making a query with a search by category name and save? Without making 2 requests.

public void save(Products products,String category){
    Criteria criteria = session.getCurrentSession().createCriteria(Categories.class);
    criteria.add(Restrictions.eq("category_name", category));
    Categories resCat =(Order) criteria.uniqueResult();

    products.setCategor(resCat);
    session.getCurrentSession().save(products);
    //This method is not suitable...
}

I need this in the form of hibernate:

INSERT INTO table1 ( column1, column2, someInt, someVarChar )
SELECT  table2.column1, table2.column2, 8, 'some string etc.'
FROM    table2
WHERE   table2.category_name = blablabla;
  • Something similar is discussed below: https://stackoverflow.com/questions/3927091/save-child-objects-automatically-using-jpa-hibernate – Mebin Joe Jan 31 '19 at 10:49
  • 1
    To be honest that does not make sense (it is possible but why would you do that) - just include ID of category in your product. Don't use product name as data but its ID - what you display to the user does not have to be the same that you put in your request. Alternatively, since you threat category name as your identifier - make it a PK. – Antoniossss Jan 31 '19 at 11:09
  • @ Antoniossss yes, I decided to do as you wrote – ЭмЭрИкс_007 Jan 31 '19 at 11:15

0 Answers0