Hibernate5 only updates the collection from many to many relationships

I have the following diagram mapped to Hibernate 5.2

Chart database

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<>();

    //Getter and Setter

}

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<>();

    //Getter and Setter

}

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?

+4
source share
2

, , .

, , , , Maciej Kowalski, .

Set, , .

@Override
@Transactional(rollbackFor = StockException.class)
public void addCategoriesToStock(Set<Integer> categoryCodes, Integer codStock) throws StockException{
    //I get the stock I'm going to associate
    Stock stock = sessionFactory.getCurrentSession().get(Stock.class, codStock);
    if (categoryCodes != null) {
    //For each category to add to the stock, I consult and add the relationship in both entities
        for (Integer codCategory : categoryCodes) {
            Category category = sessionFactory.getCurrentSession().get(Category.class, codCategory);
            category.add(stock);
            stock.add(category);
        }
    }
    sessionFactory.getCurrentSession().merge(stock);
    sessionFactory.getCurrentSession().flush();
}

@Override
@Transactional(rollbackFor = StockException.class)
public void removeCategoriesToStock(Set<Integer> categoryCodes, Integer codStock) throws StockException{
    //I get the stock that I will disassociate
    Stock stock = sessionFactory.getCurrentSession().get(Stock.class, codStock);
    if (categoryCodes != null) {
    //For each category to eliminate the stock, I consult and eliminate the relationship in both entities
        for (Integer codCategory : categoryCodes) {
            Category category = sessionFactory.getCurrentSession().get(Category.class, codCategory);
            category.remove(stock);
            stock.remove(category);
        }
    }
    sessionFactory.getCurrentSession().merge(stock);
    sessionFactory.getCurrentSession().flush();
}

, , , . , , , .

, .

0

, categories:

@Override
@Transactional(rollbackFor = StockException.class)
public void addCategoriesToStock(List<Category> categories, Stock stock) throws StockException{
    stock = sessionFactory.getCurrentSession().get(Stock.class, stock.getCodStock());
    stock.setCategories(categories);

    for(Category cat: categories){
        cat.getStocks().add(stock);
    }

    sessionFactory.getCurrentSession().merge(stock);
    sessionFactory.getCurrentSession().flush();
}

, , merge update .

.

+1

Source: https://habr.com/ru/post/1675268/


All Articles