JPA 映射似乎没问题,但 junitTest 仍然给出异常 JdbcSQLIntegrityConstraint违规异常:列 "CART_ID" 不允许空;



我得到了以下异常

org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column "CART_ID"; SQL statement ...

尽管一切似乎都映射正确,但当我调试时,应该为null的值就在那里。

这里有一个给出异常的代码和测试示例:

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

请注意,获取单个实体的测试运行良好。

问题出现在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, ?)

最新更新