I have the following diagram mapped to Hibernate 5.2

These are my entity classes:
with
@Entity
@Table(name = "stock", catalog = "mkyongdb", uniqueConstraints = {
@UniqueConstraint(columnNames = "STOCK_NAME"),
@UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "STOCK_ID", unique = true, nullable = false)
private Integer stockId;
@Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
private String stockCode;
@Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
private String stockName;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.REFRESH})
@JoinTable(name = "stock_category", catalog = "mkyongdb", joinColumns = {
@JoinColumn(name = "STOCK_ID", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "CATEGORY_ID",
nullable = false, updatable = false) })
private Set<Category> categories = new HashSet<>();
}
Category
@Entity
@Table(name = "category", catalog = "mkyongdb")
public class Category implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "CATEGORY_ID", unique = true, nullable = false)
private Integer categoryId;
@Column(name = "NAME", nullable = false, length = 10)
private String name;
@Column(name = "[DESC]", nullable = false)
private String desc;
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "categories", cascade = {CascadeType.MERGE, CascadeType.REFRESH})
private Set<Stock> stocks = new HashSet<>();
}
Everything works well.
I just need to add a list of categories to the stock. I do not want to modify the object Stock, just add or remove categories from the table stock_category.
This is my service:
@Override
@Transactional(rollbackFor = StockException.class)
public void addCategoriesToStock(Set<Category> categories, Stock stock) throws StockException{
stock = sessionFactory.getCurrentSession().get(Stock.class, stock.getCodStock());
stock.setCategories(categories);
sessionFactory.getCurrentSession().update(stock);
sessionFactory.getCurrentSession().flush();
}
This is a test for the service.
@Test
public void testAddCategoriesStock() throws Exception {
Stock newValues = new Stock();
newValues.setStockId(1);
Category category = new Category();
category.setCategoryId(13);
dao.addCategoriesToStock(new HashSet<>(Arrays.asList(category)), newValues);
List<Stock> stocks = dao.getAllStockeByCategoriesCriteria(category);
for (Stock stock : stocks) {
System.out.println(stock);
}
}
The test passes without errors, but when viewing stocks associated with the category "13" ( getAllStockeByCategoriesCriteria), it does not bring me any stocks. Then the previously performed operation did not work.
What to do to add or remove categories?