多对多的映射与额外的列持续存在的问题

时间:2016-09-05 12:33:15

标签: hibernate jpa spring-data hibernate-mapping

我有额外列的多对多映射。这里有一些带有映射的代码。

GroupEntity

@Id
@ManyToOne
@JoinColumn(name = "group_id")
private GroupEntity group;

@Id
@ManyToOne
@JoinColumn(name = "exchange_code")
private ExchangeEntity exchange;

@Column(name = "enabled")
private Boolean enabled;

GroupBrigdeEntity

@Id
@Column(nullable = false)
private String code;

@OneToMany(mappedBy = "exchange")
private Set<GroupBrigdeEntity> exchangeGroups;

ExchangeEntity

GroupEntity groupEntity = groupRepository.findOne(groupExchangeSettings.getGroupId());
    for (GroupExchange exchange : groupExchangeSettings.getExchanges()) {
        GroupBridgeEntity groupBridge = new GroupExchangeBunchEntity();
        groupBridge.setEnabled(exchange.getEnabled());
        groupBridge.setExchange(exchangeRepository.findByCode(exchange.getExchangeCode()));
        groupBridge.setGroup(groupEntity);
        groupEntity.getGroupExchanges().add(groupExchangeBunch);
    }
    groupRepository.save(groupEntity);

我的目标是获得给定ID的组并添加一些新的交换。我是这样做的:

2016-09-05 15:27:41.031  WARN 25232 --- [nio-8090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1048, SQLState: 23000
2016-09-05 15:27:41.032 ERROR 25232 --- [nio-8090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'group_id' cannot be null
2016-09-05 15:27:41.033  INFO 25232 --- [nio-8090-exec-3] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements
2016-09-05 15:27:41.034  WARN 25232 --- [nio-8090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Warning Code: 1048, SQLState: 23000
2016-09-05 15:27:41.034  WARN 25232 --- [nio-8090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'group_id' cannot be null
2016-09-05 15:27:41.034  WARN 25232 --- [nio-8090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Warning Code: 1048, SQLState: 23000
2016-09-05 15:27:41.035  WARN 25232 --- [nio-8090-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'exchange_code' cannot be null
2016-09-05 15:27:41.049 ERROR 25232 --- [nio-8090-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'group_id' cannot be null

当我运行此代码时,我得到异常

{{1}}

我猜我的GroupBrigdeEntity没有正确保存,因为它的属性在级联持久化时为null。有人能帮我吗? P.S我希望你能原谅我的英语不好。

1 个答案:

答案 0 :(得分:0)

你有一个带有多个@IdClass注释的中间类,因此对象的身份需要由em.find注释定义。对于JPA提供程序来查找此类的对象,它需要一个表示该对象的单一标识(PK)对象,因此这就是您需要一个id-class的原因 - 同样的事情将传递给{{1}}如果你想找到它。这是JPA规范和JPA documentation