杰克逊在序列化时触发 JPA 懒惰获取到目前为止已尝试
我们有一个后端组件,通过JPA向RESTful API公开数据库(PostgreSQL)数据。
问题是,当发送JPA实体作为REST响应时,我可以看到Jackson触发了所有懒惰的JPA关系。
代码示例(简化):
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")//for resolving this bidirectional relationship, otherwise StackOverFlow due to infinite recursion
public class Parent extends ResourceSupport implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
//we actually use Set and override hashcode&equals
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL)
private List<Child> children = new ArrayList<>();
@Transactional
public void addChild(Child child) {
child.setParent(this);
children.add(child);
}
@Transactional
public void removeChild(Child child) {
child.setParent(null);
children.remove(child);
}
public Long getId() {
return id;
}
@Transactional
public List<Child> getReadOnlyChildren() {
return Collections.unmodifiableList(children);
}
}
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable;
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Child implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(name = "id")
private Parent parent;
public Long getId() {
return id;
}
public Parent getParent() {
return parent;
}
/**
* Only for usage in {@link Parent}
*/
void setParent(final Parent parent) {
this.parent = parent;
}
}
import org.springframework.data.repository.CrudRepository;
public interface ParentRepository extends CrudRepository<Parent, Long> {}
import com.avaya.adw.db.repo.ParentRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.hateoas.Link;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
@RestController
@RequestMapping("/api/v1.0/parents")
public class ParentController {
private final String hostPath;
private final ParentRepository parentRepository;
public ParentController(@Value("${app.hostPath}") final String hostPath,
final ParentRepository parentRepository) {
// in application.properties: app.hostPath=/api/v1.0/
this.hostPath = hostPath;
this.parentRepository = parentRepository;
}
@CrossOrigin(origins = "*")
@GetMapping("/{id}")
public ResponseEntity<?> getParent(@PathVariable(value = "id") long id) {
final Parent parent = parentRepository.findOne(id);
if (parent == null) {
return new ResponseEntity<>(new HttpHeaders(), HttpStatus.NOT_FOUND);
}
Link selfLink = linkTo(Parent.class)
.slash(hostPath + "parents")
.slash(parent.getId()).withRel("self");
Link updateLink = linkTo(Parent.class)
.slash(hostPath + "parents")
.slash(parent.getId()).withRel("update");
Link deleteLink = linkTo(Parent.class)
.slash(hostPath + "parents")
.slash(parent.getId()).withRel("delete");
Link syncLink = linkTo(Parent.class)
.slash(hostPath + "parents")
.slash(parent.getId())
.slash("sync").withRel("sync");
parent.add(selfLink);
parent.add(updateLink);
parent.add(deleteLink);
parent.add(syncLink);
return new ResponseEntity<>(adDataSource, new HttpHeaders(), HttpStatus.OK);
}
}
因此,如果我发送GET,则响应如下:.../api/v1.0/parents/1
{
"id": 1,
"children": [
{
"id": 1,
"parent": 1
},
{
"id": 2,
"parent": 1
},
{
"id": 3,
"parent": 1
}
],
"links": [
{
"rel": "self",
"href": "http://.../api/v1.0/parents/1"
},
{
"rel": "update",
"href": "http://.../api/v1.0/parents/1"
},
{
"rel": "delete",
"href": "http://.../api/v1.0/parents/1"
},
{
"rel": "sync",
"href": "http://.../api/v1.0/parents/1/sync"
}
]
}
但是我希望它不包含或包含它作为空数组或 null - 不从数据库中获取实际值。children
该组件具有以下值得注意的 maven 依赖项:
- Spring Boot Starter 1.5.7.RELEASE - Spring Boot Starter Web 1.5.7.RELEASE (version from parent) - Spring HATEOAS 0.23.0.RELEASE - Jackson Databind 2.8.8 (it's 2.8.1 in web starter, I don't know why we overrode that) - Spring Boot Started Data JPA 1.5.7.RELEASE (version from parent) -- hibernate-core 5.0.12.Final
到目前为止已尝试
调试表明,在序列化过程中,有一个在 at 上,另一个在 on 上。select
Parent
parentRepository.findOne(id)
Parent.children
起初,我尝试应用于惰性集合,但这会忽略该集合,即使它实际上包含某些内容(已被获取)。@JsonIgnore
我发现了杰克逊数据类型休眠项目,声称
构建 Jackson 模块 (jar) 以支持 JSON 序列化和 Hibernate (http://hibernate.org) 特定数据类型和属性的反序列化;特别是延迟加载方面。
这样做的想法是将(如果使用休眠的版本5)注册到,并且应该这样做,因为模块默认设置为。Hibernate5Module
ObjectMapper
FORCE_LAZY_LOADING
false
因此,我包含了此依赖项,版本2.8.10(来自父级)。并用谷歌搜索了一种在Spring Boot中启用它的方法(我也找到了其他来源,但它们主要指的是这个)。jackson-datatype-hibernate5
1.直接添加模块(弹簧启动特定):
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HibernateConfiguration {
@Bean
public Module disableForceLazyFetching() {
return new Hibernate5Module();
}
}
调试表明,当Spring返回时,它正在调用包含此模块,并且已强制懒惰设置为false,正如预期的那样。但是,它仍然会获取 .ObjectMapper
Parent
children
进一步的调试显示:循环访问属性()并调用它们的方法,其中第一行是:这是触发延迟加载。我无法发现代码真正关心休眠模块的任何地方。com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields
com.fasterxml.jackson.databind.ser.BeanPropertyWriter
serializeAsField
final Object value = (_accessorMethod == null) ? _field.get(bean) : _accessorMethod.invoke(bean);
upd还尝试启用它应该包括懒惰属性的实际id,而不是(这是默认值)。SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS
null
@Bean
public Module disableForceLazyFetching() {
Hibernate5Module module = new Hibernate5Module();
module.enable(Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS);
return module;
}
调试显示该选项已启用,但仍然没有效果。
2. 指示 Spring MVC 添加模块:
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
@Configuration
@EnableWebMvc
public class HibernateConfiguration extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
.modulesToInstall(new Hibernate5Module());
converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}
}
这也成功地将模块添加到正在调用的模块中,但在我的情况下仍然没有效果。ObjectMapper
3. 用一个新的对象映射器完全替换对象映射器
:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class HibernateConfiguration {
@Primary
@Bean(name = "objectMapper")
public ObjectMapper hibernateAwareObjectMapper(){
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Hibernate5Module());
return mapper;
}
}
同样,我可以看到模块已添加,但这对我没有影响。
还有其他方法可以添加此模块,但是由于添加了该模块,因此我没有失败。