Java 插入子表时,外键显示null,错误无法将值null插入列
原因:com.microsoft.sqlserver.jdbc.SQLServerException:无法 将值NULL插入表格的“白名单”列中 'ECM3.dbo.WHITE_LIST_MATCHESII';列不允许空值。插入 失败了 我已经为我的问题做了很多搜索,我尝试了所有可能的解决方案,但都不起作用。我试图使用关系为Java 插入子表时,外键显示null,错误无法将值null插入列,java,sql-server,hibernate,one-to-many,Java,Sql Server,Hibernate,One To Many,原因:com.microsoft.sqlserver.jdbc.SQLServerException:无法 将值NULL插入表格的“白名单”列中 'ECM3.dbo.WHITE_LIST_MATCHESII';列不允许空值。插入 失败了 我已经为我的问题做了很多搜索,我尝试了所有可能的解决方案,但都不起作用。我试图使用关系为oneToMany的父表(白名单)插入子表(白名单匹配),但它显示了前面的错误 WhiteList.java(父级) 插入法 public void inertIntoWhi
oneToMany
的父表(白名单)插入子表(白名单匹配),但它显示了前面的错误
WhiteList.java(父级)
插入法
public void inertIntoWhiteList(String entityName, Set<Party> parties) {
Transaction tx = null;
List<WhiteListMatches> matches = new ArrayList<>();
Iterator it = parties.iterator();
while (it.hasNext()) {
Party p = (Party) it.next();
WhiteListMatches w = createWhiteListMatch(p);
matches.add(w);
}
try {
hibernateSession = getSession();
tx = hibernateSession.beginTransaction();
WhiteList whiteListEntity = new WhiteList();
whiteListEntity.setEntityName(entityName);
for (WhiteListMatches wl : matches) {
whiteListEntity.getMatches().add(wl);
}
hibernateSession.save(whiteListEntity);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
tx.commit();
hibernateSession.close();
}
}
Hibernate不会为您做任何额外的工作。所以如果你有
whiteList将
与whiteList==null
Hibernate匹配,并将该null
保存到数据库中
你可以这样做:
for (WhiteListMatches wl : matches) {
wl.setWhiteList(whiteListEntity);
whiteListEntity.getMatches().add(wl);
}
在白名单
public void addMatches(List<WhiteListMatches> matches) {
for (WhiteListMatches wl : matches) {
wl.setWhiteList(this);
this.matches.add(wl);
}
}
public void addMatches(列出匹配项){
对于(白名单匹配wl:matches){
wl.设置白名单(本);
this.matches.add(wl);
}
}
我已经尝试了您的解决方案,但仍然无法解决相同的问题!我想你的意思是白名单而不是白名单。我以前试过这个,但还是一样的错误。是的,你的解决方案与我在深入调查后发现的一致,现在它工作正常。
private WhiteListMatches createWhiteListMatch(Party party) {
WhiteListMatches whiteListMatch = new WhiteListMatches();
whiteListMatch.setMatchEntityAddress(party.getADDRESS());
if (party.getX_BIRTH_DT() != null) {
whiteListMatch.setMatchEntityDateOfBirth(party.getX_BIRTH_DT().toString());
}
whiteListMatch.setMatchEntityName(party.getENTITY_NAME());
whiteListMatch.setMatchEntityPlaceOfBirth(party.getPLACE_OF_BIRTH());
whiteListMatch.setMatchEntityYearOfBirth("" + party.getX_YEAR_OF_BIRTH());
return whiteListMatch;
}
for (WhiteListMatches wl : matches) {
wl.setWhiteList(whiteListEntity);
whiteListEntity.getMatches().add(wl);
}
public void addMatches(List<WhiteListMatches> matches) {
for (WhiteListMatches wl : matches) {
wl.setWhiteList(this);
this.matches.add(wl);
}
}