Eduardo
Eduardo

Reputation: 7141

Spring JPA NULL not allowed when inserting join table entity

I have the table structure

SELLER

| ID |

CUSTOMER

| ID |

Transaction

| ID | SELLER_ID | CUSTOMER_ID |

And I represent these by entities:

@Entity
@Table(name = "SELLER")
public class Seller {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @OneToMany(mappedBy = "seller", fetch = FetchType.LAZY, orphanRemoval = true)
    private List<Transaction> transactions;

}

@Entity
@Table(name = "CUSTOMER")
public class Customer {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @OneToMany(mappedBy = "customer", fetch = FetchType.LAZY, orphanRemoval = true)
    private List<Transaction> transactions;
}

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

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
            name = "SELLER_ID",
            insertable = false,
            updatable = false,
            nullable = false,
            foreignKey = @ForeignKey(name = "TRA_SLR_FK")
    )
    private Seller seller;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(
            name = "CUSTOMER_ID",
            insertable = false,
            updatable = false,
            nullable = false,
            foreignKey = @ForeignKey(name = "TRA_CMR_FK")
    )
    private Customer customer;

}

When I try to create a Transaction and save it using a CrudRepository:

public interface TransactionRepository extends CrudRepository<Transaction,Long> {}

Using:

Customer customer = customerRepository.findOne(1L); // Similar CrudRepository    
Seller seller = sellerRepository.findOne(1L); // Similar CrudRepository    
Transaction transaction = new Transaction(seller, customer);
transaction = transactionRepository.save(transaction);

I get the error:

NULL not allowed for column "CUSTOMER_ID"; SQL statement: insert into transaction (id) values (null) [23502-195]

Why is it not using the customer to populate the CUSTOMER_ID when I call save?

Upvotes: 2

Views: 2483

Answers (1)

Javier Toja
Javier Toja

Reputation: 1762

According to doc, properties like insertable, updateable refers to SQL generation, not to insert or update related entities.

Upvotes: 1

Related Questions