为什么jpa单向一对多关联thymeleaf还是会堆栈溢出?

user类中有个tag类的set集合;

只从user类维护关系,一对多

@OneToMany

@JoinTable(name="shuo_tag",

        inverseJoinColumns=@JoinColumn(name="tag_id"),

        joinColumns=@JoinColumn(name="shuo_id"))

private Set<Tag> tags;


Tag类中没有维护关系

然后我再html中

[[${user}]]这样获取user就会出现以下这种错误

java.lang.StackOverflowError: null

at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1012) ~[na:1.8.0_151]

at java.util.concurrent.ConcurrentHashMap.putIfAbsent(ConcurrentHashMap.java:1535) ~[na:1.8.0_151]

at java.lang.ClassLoader.getClassLoadingLock(ClassLoader.java:463) ~[na:1.8.0_151]

at java.lang.ClassLoader.loadClass(ClassLoader.java:404) ~[na:1.8.0_151]

at java.lang.ClassLoader.loadClass(ClassLoader.java:411) ~[na:1.8.0_151]

at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_151]

at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_151]

at org.thymeleaf.util.JavaScriptUtils.printObject(JavaScriptUtils.java:365) ~[thymeleaf-2.1.6.RELEASE.jar:2.1.6.RELEASE]

at org.thymeleaf.util.JavaScriptUtils.print(JavaScriptUtils.java:184) ~[thymeleaf-2.1.6.RELEASE.jar:2.1.6.RELEASE]

at org.thymeleaf.util.JavaScriptUtils.printArray(JavaScriptUtils.java:227) ~[thymeleaf-2.1.6.RELEASE.jar:2.1.6.RELEASE]
阅读 1.6k
评论
    2 个回答

    @OneToMany 有一个属性 叫fetch, 默认是LAZY

    @Target({METHOD, FIELD})
    @Retention(RUNTIME)
    public @interface OneToMany {
    
        /** (Optional) Whether the association should be lazily loaded or
         * must be eagerly fetched. The EAGER strategy is a requirement on
         * the persistence provider runtime that the associated entities
         * must be eagerly fetched.  The LAZY strategy is a hint to the
         * persistence provider runtime.
         */
        FetchType fetch() default LAZY;
    
    }
    

    所以你要直接用,需要修改为立即加载,可以这么修改:

    @OneToMany(fetch = FetchType.EAGER)

      这是thymeleaf 2的bug ,升级到thymeleaf 3可以解决此bug;

      thymeleaf2的时候是自己处理的json;
      thymeleaf3使用的jackson,jackson可以通过使用@JsonIgnoreProperties和@JsonIgnore注解解决 两个类互相引用的问题

        撰写回答

        登录后参与交流、获取后续更新提醒