Я реализовал две сущности, «script» и «libelleprerequis», я создал таблицу ассоциации «scriptlibelleprerequis» для реализации «manytomany»
При создании моей базы данных у меня есть две таблицы и моя ассоциациятаблица, содержащая "id_script" и "id_libelleprerequis"
Я создал функцию, которая позволяет мне добавлять libelleprerequis к сценарию в "ScriptController" (updateScriptLibellePrerequis). Я получаю сценарий id моего JSON с objectNode и объектом libelleprerequis.
Пример JSON:
libellePrerequis:
--> id: 1
--> libelle_prerequis: "MY LIBELLE EXAMPLE"
--> produit: {id: 1, nom: "EXEMPLE"}
--> scripts: []
--> typologie: {id: 1, nom: "EXEMPLE"}
script:
--> id: 1
--> libelleprerequiss: []
--> nom: "EXAMPLE NAME SCRIPT"
Однако в моей функции появляется ошибка в строке
"Script updateScriptLibellePrerequis = scriptRepository.save (savedScript);"
Сообщение об ошибке:
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: The 'script_id' field can not be empty (null)
Script:
@Table(name = "script")
public class Script implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "nom")
private String nom;
@OneToMany(
mappedBy = "script",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<ScriptLibellePrerequis> libelleprerequiss = new ArrayList<>();
public void addLibellePrerequis(LibellePrerequis libelleprerequis) {
ScriptLibellePrerequis scriptLibellePrerequis = new ScriptLibellePrerequis( this, libelleprerequis );
libelleprerequiss.add( scriptLibellePrerequis );
libelleprerequis.getScripts().add( scriptLibellePrerequis );
}
public void removeLibellePrerequis(LibellePrerequis libelleprerequis) {
ScriptLibellePrerequis scriptLibellePrerequis = new ScriptLibellePrerequis( this, libelleprerequis );
libelleprerequis.getScripts().remove( scriptLibellePrerequis );
libelleprerequiss.remove( scriptLibellePrerequis );
scriptLibellePrerequis.setScript( null );
scriptLibellePrerequis.setLibelleprerequis( null );
}
LibellePrerequis:
@Table(name = "libelleprerequis")
public class LibellePrerequis implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "libelle_prerequis")
private String libelle_prerequis;
@ManyToOne
private Produit produit;
@ManyToOne
private Typologie typologie;
@OneToMany(
mappedBy = "script",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<ScriptLibellePrerequis> scripts = new ArrayList<>();
ScriptLibellePrerequis:
@Table(name = "scriptlibelleprerequis")
public class ScriptLibellePrerequis implements Serializable {
@Id
@ManyToOne
private Script script;
@Id
@ManyToOne
private LibellePrerequis libelleprerequis;
public Script getScript() {
return script;
}
public void setScript(Script script) {
this.script = script;
}
public LibellePrerequis getLibelleprerequis() {
return libelleprerequis;
}
public void setLibelleprerequis(LibellePrerequis libelleprerequis) {
this.libelleprerequis = libelleprerequis;
}
И мой контроллер для добавления сценария и libelleprerequis в мою таблицу ассоциации:
@PostMapping("/create")
public ResponseEntity<Script> updateScriptLibellePrerequis(@RequestBody ObjectNode objectNode) {
Long id_script = objectNode.get("script").get("id").asLong();
String libelleprerequis = objectNode.get("libellePrerequis").toString();
ObjectMapper objectMapper = new ObjectMapper();
try {
LibellePrerequis mylibelle = objectMapper.readValue(libelleprerequis, LibellePrerequis.class);
Optional<Script> scriptData = scriptRepository.findById(id_script);
if (scriptData.isPresent()) {
Script savedScript = scriptData.get();
savedScript.addLibellePrerequis(mylibelle);
Script updateScriptLibellePrerequis = scriptRepository.save(savedScript);
return new ResponseEntity<>(updateScriptLibellePrerequis, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}