使用Spring Boot 的问题总结

问题一: Spring Boot 使用 JPA时, Controller中访问数据库表并以(ResponseBody)展示到浏览器时出现问题

HTTP Status 500 - Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.SerializationFeature.FAIL_ON_EMPTY_BEANS) ) 

----- 实体类User(对应数据库中的tb_user)

//使用JPA
@Entity                    //是一个跟数据库对应的类
@Table(name="tb_user")    //指定生成的表名
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)     //主键id自增长
    private Integer id;

    @Column(name = "email")
    private String email;

    @Column(name = "last_name", length = 50)    //驼峰命名法, 并约定最长长度为50
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
//只需要继承JpaRepository类, 便可使用数据库的CRUD,分页以及排序操做
//<User,Integer> 表示的是操作的实体类, 以及主键类型
public interface UserRepository extends JpaRepository<User, Integer> {
}

application.yml配置文件

spring:
  datasource:
    username: root
    password: *****
    url: **************
    driver-class-name: com.mysql.jdbc.Driver
  # 更新或者创建表结构
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

--UserController类, 有一个用于用id查找User的方法, 并以Json的方式返回给浏览器显示

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") int id)
    {
        User user = userRepository.getOne(id);
        return user;
    }
}

然后.....  一访问,浏览器便出现了


Intellij idea 中



大概就是: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.gdufe.entity.User_$$_jvst21_0["handler"])

然后谷歌了一下: 发现问题好像是因为实体在加载完全之前就加载了惰性和序列化。

解决方法就是: 在User类上加一个注释

@JsonIgnoreProperties({
    
    "hibernateLazyInitializer", "handler"})
如下图

通过设置hibernate代理对象延迟加载。通过注释该类具有延迟加载的私有属性来绕过它

问题解决


猜你喜欢

转载自blog.csdn.net/qq_31281327/article/details/80086517