JPAMap看起来不错,但是junitTest仍然给予异常JdbcSQLIntegrityConstraintViolationException:列“CART_ID”不允许为NULL;

dtcbnfnu  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(113)

我得到了以下异常
第一个月
即使一切似乎Map正确,当我调试的值,应该是空的是存在的。
下面是给出该异常的代码和测试示例:

@Entity
@Table(name = "ITEM")
@Setter
public class ItemEntity {
    
    //...
    private CartEntity cart;

    public ItemEntity() {}
    
    // getters and setters
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name = "cart_id", nullable = false, insertable = false, updatable = false)
    public CartEntity getCart()
    {
        return cart;
    }
}


@Entity
@Table(name="CART")
@Setter
public class CartEntity {

    //...
    private List<ItemEntity> items;

    // getters and setters
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "cart")
    @OrderColumn(name = "RANK")
    public List<ItemEntity> getItems()
    {
        return items;
    }
}

@Repository
public interface ItemEntityRepository
    extends JpaRepository<ItemEntity, Long>
{
}

这里的测试仍然给予空值,即使在调试值时也是如此

@Execution(ExecutionMode.CONCURRENT)
@DataJpaTest(showSql = false)
class ItemEntityRepositoryTest
{
    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private ItemEntityRepository repository;
    
    private Long entityId;
        
    @BeforeEach
    void init()
    {
        Item item = new Item();
        // ... fill other item attributes here
    
        CartEntity cart = new CartEntity();
        // ... fill other cart attribute here

        Long idSet = (Long) entityManager.persistAndGetId(cart);
        cart.setId(idSet);
        cart.setItems(Collections.singletonList(item));

        item.setCompetitionConfigurationSet(cart);

        entityId = (Long) entityManager.persistAndGetId(item);
    }

    @Test
    void findAll_existingItems_returnsAllItems()
    {
        List<Items> items = repository.findAll();
        assertEquals(1, items.size());
    }
}

注意,获取单个实体的测试工作正常。

5us2dqdw

5us2dqdw1#

getCart()中的insertable = false存在问题。Hibernate无法在项目中插入cart_id值。
更多详情:
如果启用SQL日志记录:

spring.jpa.properties.hibernate.show_sql=true
logging.level.org.hibernate.orm.jdbc.bind=trace

您将获得:

Hibernate: insert into cart (id) values (default)
Hibernate: insert into item (id) values (default)
2022-12-21T19:50:53.196+03:00  WARN 9892 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 23502, SQLState: 23502
2022-12-21T19:50:53.196+03:00 ERROR 9892 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : NULL not allowed for column "CART_ID"

如果删除insertable = false,代码将正常工作。项的SQL语句将有所不同:

Hibernate: insert into item (id, cart_id) values (default, ?)

相关问题