我在休眠状态下建立一对多关系,但是当我尝试插入一个值时 在表中,我得到一个例外,即我的FK in photos实体不能为null。
我的父实体:
@Table(name = "library")
@Entity
public class Book {
@OneToMany(
fetch = FetchType.LAZY,
mappedBy = "book",
cascade = CascadeType.ALL,
orphanRemoval = true
)
// setters / getters and other columns
我的孩子实体
@Entity
@Table(name = "photos")
public class photos{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "idphotos")
private int id;
@ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
@JoinColumn(name = "library_idlibrary")
private Book book;
// other columns
例外:
java.sql.SQLIntegrityConstraintViolationException: Column 'library_idlibrary' cannot be null
com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:115)
com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)
com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1066)
我有要插入值的DAO对象和控制器:
控制器:
@PostMapping( value = "/newBook",consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String add(@ModelAttribute("book") @Valid Book book, HttpServletResponse response, HttpServletRequest request,@RequestParam(value = "photo", required = false) List<MultipartFile> photos, @RequestParam(value = "valute",required = false) String valute,BindingResult result) {
if (result.hasErrors()) {
return "addBook";}
List<entity.photos> list = new ArrayList<>();
for (MultipartFile photo : photos) {
File file =null;
if (!photo.isEmpty()) {
try {
validateImg(photo);
file = new File(context.getRealPath("/uploadFile/" + photo.getOriginalFilename()));
Logger.getAnonymousLogger().info("THE PATH IS " + file.getAbsolutePath());
FileUtils.copyInputStreamToFile(photo.getInputStream(), file);
file.createNewFile();
} catch (IOException ex) {
result.reject("uk_UA", "Поганий тип");
return "addBook";
}
}
if (file != null) {
photos ph = new photos(photo.getOriginalFilename());
StringBuilder builder = new StringBuilder();
builder.append(file.getAbsolutePath());
Logger.getAnonymousLogger().info("SOMETHING HAS BROKEN IN LOGGING FILE");
System.out.println("INSIDE ADD METHOD ");
list.add(ph);
} else list.add(new photos(""));
}
book.getPhotosList().addAll(list);
service.add(book);
return "redirect:/books";
}
DAO:
public void add(Book user) {
currentSession().save(user);
}
答案 0 :(得分:2)
很可能您尚未将“照片”中的后向引用设置为“书”,然后通过“照片”集合将“书”中的持久/合并操作进行级联。将元素添加到集合时,需要保持关系的双方。例如:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
kv = """
<CustomDropdown>:
size_hint_y: None
pos_hint: {"top": 1}
height: 56.0
orientation: "horizontal"
TextInput:
id: txt_input
size_hint_x: 0.5
Button:
id: show_drop
size_hint_x: 0.2
text: "drop"
on_release: root.show_dropdown()
Button:
id: submit_btn
size_hint_x: 0.3
text: "Submit"
on_press: root.validate_txt()
"""
class CustomDropdown(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.dropdown = DropDown()
self.fakeValues = ["First", "Second", "Third"]
for val in self.fakeValues:
btn = Button(text=val, size_hint=[0.5, None])
btn.height = 56.0
btn.bind(on_press=self.change_value)
self.dropdown.add_widget(btn)
def change_value(self, *args):
self.ids.txt_input.text = args[0].text
self.hide_dropdown()
def add_options(self, *args):
btn = Button(text=args[0], size_hint=[0.5, None])
btn.height = 56.0
btn.bind(on_press=self.change_value)
self.dropdown.add_widget(btn)
def validate_txt(self, *args):
curText = self.ids.txt_input.text
if ((curText in self.fakeValues) or (curText == None) or (curText == "")):
return
self.fakeValues.append(curText)
self.add_options(curText)
self.hide_dropdown()
def hide_dropdown(self):
self.dropdown.dismiss()
def show_dropdown(self, *args):
if self.dropdown.parent:
self.hide_dropdown()
else:
self.dropdown.open(self.ids.txt_input)
class TestApp(App):
def build(self):
Builder.load_string(kv)
return CustomDropdown()
TestApp().run()