springboot+hibernate开发中的坑

1. Springboot2.0 限制文件上传的配置:百度都是针对Springboot1.x的.

# MULTIPART (MultipartProperties)
spring.servlet.multipart.enabled=true # Whether to enable support of multipart uploads.
spring.servlet.multipart.file-size-threshold=0 # Threshold after which files are written to disk. Values can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes, respectively.
spring.servlet.multipart.location= # Intermediate location of uploaded files.
spring.servlet.multipart.max-file-size=1MB # Max file size. Values can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes, respectively.
spring.servlet.multipart.max-request-size=10MB # Max request size. Values can use the suffixes "MB" or "KB" to indicate megabytes or kilobytes, respectively.
spring.servlet.multipart.resolve-lazily=false # Whether to resolve the multipart request lazily at the time of file or parameter access.

其他配置可以查看官网

2. SpringBoot内嵌的Tomcat对上传文件有限制,会切断Responese的响应。

需要自己创建新的ConnectorsEnable Multiple Connectors with Tomcat

3.swagger2碰到 @manytomany,启动会出现错误

Springfox 2.7.0 with M:n-Relation; Failed to start bean 'documentationPluginsBootstrapper'; nested exception is com.google.common.util.concurrent.ExecutionError: java.lang.StackOverflowError

暂时没有办法解决:官方是这么回复

4.jackson碰到@manytomany双向关联,response会出现循环引的溢出

同Jackson的注解,允许一方管理关系。通过注解@JsonManagedReference``@JsonBackReference
参考详细
http://www.sonymoon.com/archives/92

5. 使用注解@JsonManagedReference,@JsonBackReference,前台提交application/json;charset=UTF-8,后台会有错误

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported

通过注解@JsonIgnore,将其中一方忽略 

6. @PutMapping不能获取参数,为null

@PutMapping获取参数的方式和PostMapping不一样

## 7. 在继承QuartzJobBean的任务类中,如果使用类JPA
实体类是@ManyToMany,注意user.getOrganizations。不能注入Service

“`java
public class SampleJob extends QuartzJobBean {

private String name;

// Invoked if a Job data map entry with that name
public void setName(String name) {
    this.name = name;
}

@Override
protected void executeInternal(JobExecutionContext context)
        throws JobExecutionException {

    UserService userService = Global.applicationContext.getBean(UserService.class);
    User user = userService.findById(1);

    System.out.println(String.format("Hello %s! time is %s", this.name,
            new SimpleDateFormat("HH:mm:ss").format(new Date())) + " -> " + user.getOrganizations());
}

}
异常信息
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.yodean.oa.sys.user.entity.User.organizations, could not initialize proxy – no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:582) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:201) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:561) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:132) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:299) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final]
at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_111]
at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_111]
at com.yodean.oa.common.job.SampleJob.executeInternal(SampleJob.java:33) ~[classes/:na]
at org.springframework.scheduling.quartz.QuartzJobBean.execute(QuartzJobBean.java:75) ~[spring-context-support-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.3.0.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.3.0.jar:na]

2018-03-23 17:43:50.952 ERROR 77460 — [ryBean_Worker-1] org.quartz.core.ErrorLogger : Job (TASK.t1 threw an exception.“`

[http://codrspace.com/Khovansa/spring-quartz-with-a-database/](http://codrspace.com/Khovansa/spring-quartz-with-a-database/)
[https://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring](https://stackoverflow.com/questions/6990767/inject-bean-reference-into-a-quartz-job-in-spring)
[https://stackoverflow.com/questions/32336152/spring-boot-quartz-lazyinitializationexception](https://stackoverflow.com/questions/32336152/spring-boot-quartz-lazyinitializationexception)

## 8. jackson标签`@JsonIgnore`
* 我之前认为response的时候只是不会打印出去。
* 但是我发现,有注解`@JsonIgnore`的字段,使用`@RequestBody`,接受参数有问题。**接受不到**

## 9. SpringMVC @RequestBody 用map接收请求参数的问题解决
用`@RequestParam`,然后就对了。。对了。。了。。**这个注解必须要写**
```java
 @GetMapping("/tree")
    public Result<List<TreeNode>> getOrgsAsTree(@RequestParam Map<String, Object> params) {

    }

Set<Integer> List<Integer>接收参数都必须加注解@RequestParam
JavaBean,Integer[]等基本类型可以不用加

集合类不写注解会抛出异常

No primary or default constructor found for interface java.util.Set

10 JPA扩展Repository

http://www.baeldung.com/spring-data-jpa-method-in-all-repositories

注意在实现方法上,必须使用注解@Transactional
不然保存会失败

@Transactional
    public void updateNonNull(T t) {

        try {
            ID id = (ID)PropertyUtils.getProperty(t, "id");
            T persist = findById(id).get();
            NullAwareBeanUtilsBean.getInstance().copyProperties(persist, t);
            save(persist);
        } catch (Exception e) {
            throw new OAException(ResultEnum.UNKNOW_ERROR);
        }
    }

11 JPA 实体类最佳实践

如果字段名和数据库列名不对应,要显示地写出@column

   @Column(name = "user_id")
    private Integer userId;

不然在使用注解,无法正常启动

uniqueConstraints = {@UniqueConstraint(columnNames={"category", "category_id", "user_id", "del_flag"})}

12 用List Set代替数组

13 Entity类中用String代替Character

14 SpringBoot 消息推送(SSE)

spring封装了对sse的操作
https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/sse-emitter.html

15 文件预览

office在线预览: https://blogs.office.com/en-us/2013/04/10/office-web-viewer-view-office-documents-in-a-browser/
office 转pdf -> mozilla/pdf.js 查看pdf文件

  • 如何word转pdf
    1. 安装libreoffice
      yum install libreoffice
    2. 执行命令
soffice --headless --invisible --convert-to pdf /mnt/a.docx --outdir /mnt

参考链接http://bakcom.iteye.com/blog/2397446
* 乱码解决方案

参考链接:https://blog.csdn.net/wlwlwlwl015/article/details/51482065