我正在插入使用CSV
选择的JFileChooser
文件。导入时出错,显示主键IS NULL
。它是自动递增(我使用和SQL命令)。奇怪的是,完全相同的插入代码适用于同一数据库中的不同表。这是我到目前为止的代码:
JAVA CODE
int returnVal = fileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
Scanner sin = new Scanner(new FileReader(new File(file.getName())));
while (sin.hasNext()) {
String[] line = sin.nextLine().split(",");
String name = line[0];
String surname = line[1];
int age = Integer.parseInt(line[2]);
String gender = line[3];
String shoeSize = line[4];
Studentstbl st = new Studentstbl();
st.setAge(age);
st.setDonationStatus("N");
st.setFirstName(name);
st.setGender(gender);
st.setShoeSize(shoeSize);
st.setSurname(surname);
yritpatPUEntityManager.getTransaction().begin();
yritpatPUEntityManager.persist(st);
yritpatPUEntityManager.getTransaction().commit();
studentstblList.clear();
studentstblList.addAll(studentstblQuery.getResultList());
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(jPanel1, "A problem occured when accessing the file "+file.getAbsolutePath(), "Error", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(jPanel1, "Cancelled by user", "Error", JOptionPane.ERROR_MESSAGE);
}
SQL
create table studentstbl (
student_id int not null primary key
GENERATED ALWAYS AS IDENTITY
(START WITH 1, INCREMENT BY 1),
school_id int not null,
first_name varchar(60) not null,
surname varchar(60) not null,
age int not null,
gender varchar(1) not null,
shoe_size int not null,
donation_status varchar(1) not null)
和
ALTER TABLE STUDENTSTBL
ADD CONSTRAINT SCHOOL_ID FOREIGN KEY (SCHOOL_ID)
REFERENCES SCHOOLSTBL
(SCHOOL_ID)
CSV
aname,asname,2,M,1
bname,bsname,3,F,1
cname,csname,4,F,2
dname,dsname,5,F,3
ename,esname,7,M,3
fname,fsname,6,M,3
gname,gsname,8,F,4
hname,hsname,10,M,4
iname,isname,9,M,4
jname,jsname,14,F,7
kname,ksname,12,F,6
lname,lsname,13,F,6
mname,msname,3,F,1
nname,nsname,2,M,1
oname,osname,15,F,6
pname,psname,15,M,6
qname,qsname,12,M,4
rname,rsname,8,M,3
sname,ssname,7,M,3
tname,tsname,6,F,3
uname,usname,5,F,2
vname,vsname,14,M,6
wname,wsname,12,M,6
xname,xsname,6,F,2
yname,ysname,8,M,2
zname,zsname,7,M,2
答案 0 :(得分:0)
我今天在学校设法解决了这个问题!我在Studentstbl中硬编码了一个.get语句,修复了我的其他一个错误并导致了这个错误。删除实体,列表和查询并再次导入它们非常有效。