Question 1: When Spring Boot uses JPA, there is a problem when accessing the database table in the Controller and displaying it to the browser as (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) )
----- Entity class User (corresponding to tb_user in the database)
//使用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 configuration file
spring:
datasource:
username: root
password: *****
url: **************
driver-class-name: com.mysql.jdbc.Driver
# 更新或者创建表结构
jpa:
hibernate:
ddl-auto: update
show-sql: true
--UserController class, there is a method to find User by id, and return it to the browser for display in 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;
}
}
Then... as soon as you visit, the browser appears
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"])
Then Googled it a bit: I found that the problem seemed to be because the entity was loaded with laziness and serialization before it was fully loaded.
The solution is: add a comment on the User class
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler"})
如下图
Delay loading by setting the hibernate proxy object. By annotating that the class has a private property of delayed loading to bypass it
problem solved