Spring Data JPA много ко многим с лишними столбцами orphanRemoval не работает - PullRequest
0 голосов
/ 05 февраля 2019

У меня есть два предмета с отношениями «многие ко многим».

CommercialePiece -)-------------(- Transaction

Им нужна дополнительная информация, поэтому я создал объединяемую таблицу с именем piecetransaction

Итак, отношения становятся -------- один ко многим

CommercialePiece -|-----------(- piecetransaction -)------------|- Transaction

структура таблиц примерно такая:

+-----------------------+  +---------------------- + +----------------------+
+ commercialepiece      +  + piecetransaction      + + transaction          +
+-----------------------+  +---------------------- + +---------------- -----+
+ id_piece   -- pk      +  + id_transaction -pk/fk + + id_transaction -- pk +
+ other informations    +  + id_piece       -pk/fk + +  other informations  +
+                       +  + other informations    + +                      +
+-----------------------+  +---------------------- + +----------------------+

Теперь отображение:

 @Entity(name = "commercialepiece")
    @Table(name = "commercialepiece")
    @Inheritance(strategy = InheritanceType.JOINED)
    public abstract class CommercialePiece {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
     @Column(name = "idpiece")
    private Long idPiece;

     @OneToMany(mappedBy = "commercialepiece", cascade = 
     cascadeType.ALL,orphanRemoval = true)
        Set<CommercialePieceTransaction> commercialePieceTransactions = new 
     HashSet<CommercialePieceTransaction>();


    // Getter and Setter and



public void removeTransaction(Transaction transaction) {
        for (Iterator<CommercialePieceTransaction> iterator = commercialePieceTransactions.iterator(); iterator.hasNext(); ) {
            CommercialePieceTransaction commercialePieceTransaction = iterator.next();
            if (commercialePieceTransaction.getTransaction().equals(transaction)
                    && commercialePieceTransaction.getCommercialepiece().equals(this)
                    ) {
                iterator.remove();
                commercialePieceTransaction.getTransaction().getCommercialePieceTransactions().remove(commercialePieceTransaction);
                commercialePieceTransaction.setTransaction(null);
                commercialePieceTransaction.setCommercialepiece(null);
                break;
            }
        }
    }


     @Override
     public boolean equals(Object o) {


            if (o == this) return true;
            if (!(o instanceof CommercialePiece)) {
                return false;
            }

            CommercialePiece that = (CommercialePiece) o;

            return
                    Objects.equals(this.idPiece, that.idPiece);
        }


        @Override
        public int hashCode() {
            return Objects.hash(idPiece);
        }
    }

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

@Entity()
@Table(name = "piecetransaction")
@IdClass(CommercialePieceTransactionId .class)
public class CommercialePieceTransaction {



    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_piece")
    private CommercialePiece commercialepiece;

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "id_transaction")
    private Transaction transaction;

   @Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass())
            return false;

        CommercialePieceTransaction that = (CommercialePieceTransaction) o;
        return true;
    }

    @Override
    public int hashCode() {
        return Objects.hash(commercialepiece, transaction);
    }
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

@Embeddable
public class CommercialePieceTransactionId implements Serializable {

    // @Column(name = "id_piece")
    private Long commercialepiece;

    //  @Column(name = "id_transaction")
    private Long transaction;

@Override
    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass())
            return false;

        CommercialePieceTransactionId that = (CommercialePieceTransactionId) o;
        return Objects.equals(commercialepiece, that.commercialepiece) &&
                Objects.equals(transaction, that.transaction);
    }

    @Override
    public int hashCode() {
        return Objects.hash(commercialepiece, transaction
        );
    }
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

@Entity(name = "transaction")
@Table(name = "transaction")
public class Transaction {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "idtransaction")
    private Long idTransaction;

@Override
    public String toString() {
        return description;
    }


    @Override
    public boolean equals(Object o) {


        if (o == this) return true;
        if (!(o instanceof Transaction)) {
            return false;
        }

        Transaction that = (Transaction) o;

        boolean equleq = Objects.equals(this.idTransaction, that.idTransaction);
        return equleq;

    }


    @Override
    public int hashCode() {
        return Objects.hash(idTransaction);
    }

Всебыло хорошо, когда я сохраняю CommercialePiece с транзакцией

 @Test
    public void insertCommercialePieceTransaction() {
        CommercialePiece commercialePiece = commercialePieceRepository.findById(1L).get();
        Transaction transaction = transactionRepository.findById(2L).get();


        commercialePiece.addTransaction(transaction);

        commercialePieceRepository.save(commercialePiece);


    }

вставка в штук транзакции (наблюдение, транш, id_piece, id_transaction) значения (?,?,?,?)

Но когда я удаляю транзакцию из CommercialePiece, ничего не работает

 @Test
    public void detachTransactionFromCommercialePiece() {
        PurchasePiece commercialePiece = purchasePieceRepository.findById(1L).get();
        Transaction transaction = transactionRepository.findById(1L).get();
        commercialePiece.removeTransaction(transaction);
        purchasePieceRepository.save(commercialePiece);





    }

Вывод:

2019-02-09 12:59:05 DEBUG org.hibernate.SQL - 
    select
        commercial0_.id_piece as id_piece1_21_0_,
        commercial0_.id_transaction as id_trans2_21_0_,
        commercial0_.observation as observat3_21_0_,
        commercial0_.tranche as tranche4_21_0_ 
    from
        piecetransaction commercial0_ 
    where
        commercial0_.id_piece=? 
        and commercial0_.id_transaction=?
2019-02-09 12:59:06 DEBUG org.hibernate.SQL - 
    select
        commercial0_.id_piece as id_piece1_21_0_,
        commercial0_.id_transaction as id_trans2_21_0_,
        commercial0_.id_piece as id_piece1_21_1_,
        commercial0_.id_transaction as id_trans2_21_1_,
        commercial0_.observation as observat3_21_1_,
        commercial0_.tranche as tranche4_21_1_ 
    from
        piecetransaction commercial0_ 
    where
        commercial0_.id_piece=?
2019-02-09 12:59:06 DEBUG org.hibernate.SQL - 
    select
        transactio0_.idtransaction as idtransa1_36_0_,
        transactio0_.idaccount as idaccoun7_36_0_,
        transactio0_.transaction_uid as transact8_36_0_,
        transactio0_.datetransaction as datetran2_36_0_,
        transactio0_.description as descript3_36_0_,
        transactio0_.direction as directio4_36_0_,
        transactio0_.idpaymentmethod as idpaymen9_36_0_,
        transactio0_.idperson as idperso10_36_0_,
        transactio0_.idtypetransaction as idtypet11_36_0_,
        transactio0_.value as value5_36_0_,
        transactio0_.transaction_write_date as transact6_36_0_,
        transactio0_.transaction_wuid as transac12_36_0_ 
    from
        transaction transactio0_ 
    where
        transactio0_.idtransaction=?
2019-02-09 12:59:06 WARN  o.h.e.i.StatefulPersistenceContext - HHH000179: Narrowing proxy to class com.abdofx.demo.model.purchase.Supplier - this 

перерывы операций ==

Каскадудалить не работающий ее,
После этого ожидается, что удалится таблица данных piecetransaction данных. Итак, piecetransaction больше не ссылается на транзакцию с идентификатором 1 и commercialePiece с идентификатором 1;

Итак, в чем ее проблема?Я пытался решить эту проблему 4 дня, но безуспешно,

Я вдохновил некоторые идеи @Vlad Mihalcea

https://github.com/vladmihalcea/high-performance-java-persistence/blob/master/core/src/test/java/com/vladmihalcea/book/hpjp/hibernate/association/BidirectionalManyAsOneToManyWithoutEmbeddedIdTest.java

https://vladmihalcea.com/the-best-way-to-map-a-many-to-many-association-with-extra-columns-when-using-jpa-and-hibernate/

...