我的用户DTO中有以下映射来存储Map
用户属性:
@Entity(name = "User")
public class User{
@Id
@Column(name = "Id")
private long userId;
@OneToMany
@JoinColumn(name = "properties")
private Map<Long, Property> properties= new LinkedHashMap<Long, LkpAIT>();
}
@Entity(name = "Property")
public class Property{
@Id
@Column(name = "Id")
private long propertyId;
@Column(name = "Name")
private String propertyName;
}
以下@Controller方法
@RequestMapping(value = "/getUser", produces = "application/json", method = RequestMethod.GET)
public @ResponseBody Page<LkpFeed> getLookupFeeds(Model model) {
page = 1;
Page<User> users = userRepo.getUsers(new PageRequest(page, 100)); //returns 100 users
return feeds;
}
@Controller方法执行正常(找到所有用户)但是当return语句执行时,我收到以下错误:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.myapp.dto.Properties.properties, could not initialize proxy - no Session
org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:575)
org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:214)
org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:155)
org.hibernate.collection.internal.PersistentMap.isEmpty(PersistentMap.java:145)
com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:399)
com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:27)
com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:505)
com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:639)
com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:152)
com.fasterxml.jackson.databind.ser.impl.IndexedListSerializer.serializeContents(IndexedListSerializer.java:100)
基于异常我的属性字段是导致错误的原因。我已尝试使用fetchTypes
和PersistenceContexts
但我目前处于亏损状态。有什么想法吗?
答案 0 :(得分:1)
你可以做几件事
在@OneToMany
@Entity(name = "User")
public class User{
@Id
@Column(name = "Id")
private long userId;
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name = "properties")
private Map<Long, Property> properties= new LinkedHashMap<Long, LkpAIT>();
}
或者,如果您只想列出用户,则不希望在返回的JSON中使用“属性”。您可以为@JsonIgnore
properties
@Entity(name = "User")
public class User{
@Id
@Column(name = "Id")
private long userId;
@JsonIgnore
@OneToMany
@JoinColumn(name = "properties")
private Map<Long, Property> properties= new LinkedHashMap<Long, LkpAIT>();
}