简体   繁体   English

列类型为long且具有Null值的JPA实体

[英]JPA entity with column of type long that have a Null value

I'm new to JPA . 我是JPA的新手。 I'm using spring data and I want to create an entity "File" (a folder is a File ) . 我正在使用spring数据,并且想创建一个实体“ File”(文件夹是File)。 each File can have a parent (or not). 每个文件可以有一个父(或没有)。 this is my table's columns :id ,name,path ,mtime ,parentid. 这是我表的列:id,name,path,mtime,parentid。

I used this in my entities 我在实体中使用了这个

@ManyToOne
 @JoinColumn(name = "parentid")
 private File parent;

    public File() {}

    public File(String name, String path,File parent) {
        this.name = name;
        this.path=path;  
        this.parent=parent;
    }

         @Override
        public String toString() {
            return String.format(
                    "File[ id=%d,name='%s', path='%s',parentid=%d]",
                    id,name, path,parent.id);
        }

in my test I did this : 在我的测试中,我这样做:

     fileRepository.save(new File("file1","file1",null));
    File file1=fileRepository.findOne((long) 1);
    fileRepository.save(new File("file2","file2",file1));

and it inserted the first line with parentid NULL and a second line with parentid 1 (the first file).( I confirmed that on phpmyadmin) 并在第一行插入了具有parentid NULL的第一行,并在第二行插入了parentid 1(第一个文件)。

I wanted to show the lines so i did this : 我想显示线条,所以我这样做了:

for (Object element : Lists.newArrayList(fileRepository.findAll())) {
        System.out.println(element);
    }

but it doesn't work . 但这没用。 when I removed parentid from my toString() function I get the correct result : 当我从toString()函数中删除parentid时,我得到了正确的结果:

File[ id=1,name='file1', path='file1']
File[ id=2,name='file2', path='file2']

I get the same problem if I add a new column of type Long and when one of the lines have a NULL value in that column . 如果我添加一个新的类型为Long的列,并且其中一行中的一行具有NULL值,则会遇到相同的问题。 how Can I fix that ? 我该如何解决?

Your toString() method "doesn't work" because you're trying to get the id of a null parent, which obviously causes a NullPointerException. 您的toString()方法“无效”,因为您试图获取空父代的ID,这显然会导致NullPointerException。 You need to test if the parent is null before trying to get and print its ID. 您需要先测试父级是否为空,然后再尝试获取并打印其ID。 Reading the message, type and stack trace of the exception would have allowed you to find this out. 阅读消息,异常的类型和堆栈跟踪将使您能够发现这一点。 Using a debugger as well. 也使用调试器。

A variable of type long can't hold null . long类型的变量不能包含null Primitive types are not nullable. 基本类型不可为空。 So you need to use the type java.lang.Long for this field. 因此,您需要为此字段使用类型java.lang.Long

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM