- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Spring Boot 1.5.10、Spring Data JPA 和 Hibernate。
当我按 Id 搜索实体 Person 时,结果是正确的,但是当我尝试使用 List 构建查询时,我的请求返回异常:
Failed to write HTTP message:
org.springframework.http.converter.HttpMessageNotWritableException:
Could not write JSON: failed to lazily initialize a collection of role: us.icitap.entities.tims.Person.otherNames, could not initialize proxy - no Session;
nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: us.icitap.entities.tims.Person.otherNames, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->us.icitap.entities.tims.Person["otherNames"])
我正在处理的实体的代码:
@Entity
@Table(name="PERSON", schema = "TIMS")
@NamedQuery(name="Person.findAll", query="SELECT p FROM Person p")
public class Person extends PersonAbstract {
private static final long serialVersionUID = 1L;
//bi-directional many-to-one association to PersonOtherName
@OneToMany(mappedBy="person")
private List<PersonOtherName> otherNames;
//bi-directional many-to-one association to Photo
@OneToMany(mappedBy="person")
private List<Photo> photos;
//bi-directional many-to-one association to TravelDocument
@OneToMany(mappedBy="person")
private List<TravelDocument> travelDocuments;
public Person() {
}
public List<PersonOtherName> getOtherNames() {
return this.otherNames;
}
public void setOtherNames(List<PersonOtherName> otherNames) {
this.otherNames = otherNames;
}
public PersonOtherName addOtherName(PersonOtherName otherName) {
getOtherNames().add(otherName);
otherName.setPerson(this);
return otherName;
}
public PersonOtherName removeOtherName(PersonOtherName otherName) {
getOtherNames().remove(otherName);
otherName.setPerson(null);
return otherName;
}
public List<Photo> getPhotos() {
return this.photos;
}
public void setPhotos(List<Photo> photos) {
this.photos = photos;
}
public Photo addPhoto(Photo photo) {
getPhotos().add(photo);
photo.setPerson(this);
return photo;
}
public Photo removePhoto(Photo photo) {
getPhotos().remove(photo);
photo.setPerson(null);
return photo;
}
public List<TravelDocument> getTravelDocuments() {
return this.travelDocuments;
}
public void setTravelDocuments(List<TravelDocument> travelDocuments) {
this.travelDocuments = travelDocuments;
}
public TravelDocument addTravelDocument(TravelDocument travelDocument) {
getTravelDocuments().add(travelDocument);
travelDocument.setPerson(this);
return travelDocument;
}
public TravelDocument removeTravelDocument(TravelDocument travelDocument) {
getTravelDocuments().remove(travelDocument);
travelDocument.setPerson(null);
return travelDocument;
}
}
服务的相关部分:
@SuppressWarnings("unchecked")
@Override
public List<Person> searchByExpression(List<Criterion> expressions) {
Session session = entityManager.unwrap(Session.class);
List<Person> persons = null;
try {
Criteria criteria = session.createCriteria(Person.class);
for (Criterion simpleExpression : expressions) {
criteria.add(simpleExpression);
}
persons = criteria.list();
}catch (Exception e) {
e.printStackTrace();
}
session.close();
return persons;
}
@Override
public Person searchPersonById(Long id) {
return personRepository.findOne(id);
}
Controller :
@RestController
@RequestMapping("/tims/person")
public class PersonController {
@Autowired
private PersonService personService;
@RequestMapping(value="/searchPersonById/{id}", method = RequestMethod.GET)
public ResponseEntity<Person> searchById(@PathVariable("id") Long id) {
try {
Person person = this.personService.searchPersonById(id);
if (person == null)
return new ResponseEntity<Person>(null, null, HttpStatus.NOT_FOUND);
else
return new ResponseEntity<Person>(person, null, HttpStatus.OK);
}catch(Exception e){
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Exception", e.getMessage());
ResponseEntity<Person> respond = new ResponseEntity<Person>(null, httpHeaders, HttpStatus.INTERNAL_SERVER_ERROR);
return respond;
}
}
@RequestMapping("/searchPersonByGenerality")
public ResponseEntity<List<Person>> searchPersonByGenerality(String pid, String name, String surname, GenderEnum gender, String dateOfBirth){
List<Person> persons = null;
Date date = null;
try {
if(dateOfBirth != null) {
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy");
date = df.parse(dateOfBirth);
}
}catch (Exception e) {
System.err.println(e.getMessage());
}
try {
if (pid != null && !pid.isEmpty()) {
persons = this.personService.searchPersons(pid, name, surname, gender, date);
return new ResponseEntity<List<Person>>(persons, null, HttpStatus.OK);
}
int valid = 0;
List<Criterion> expressions = new ArrayList<>();
if(name != null & !name.isEmpty()) {
name = name.toUpperCase();
valid = valid + 5;
if (name.contains("%") || name.contains("_")) {
expressions.add(Restrictions.sqlRestriction("translate({alias}.name, 'ËÇ', 'EC') like '" + MyString.transformAccentsLetter(name) + "'"));
}else
expressions.add(Restrictions.sqlRestriction("translate({alias}.name, 'ËÇ', 'EC') = '" + MyString.transformAccentsLetter(name) + "'"));
}
if(surname != null & !surname.isEmpty()) {
surname = surname.toUpperCase();
valid = valid + 5;
if (surname.contains("%") || surname.contains("_")) {
expressions.add(Restrictions.sqlRestriction("translate({alias}.surname, 'ËÇ', 'EC') like '" + MyString.transformAccentsLetter(surname) + "'"));
}else
expressions.add(Restrictions.sqlRestriction("translate({alias}.surname, 'ËÇ', 'EC') = '" + MyString.transformAccentsLetter(surname) + "'"));
}
if (gender != null) {
valid = valid + 2;
expressions.add(Restrictions.eq("gender", gender));
}
if (date != null) {
valid = valid + 3;
expressions.add(Restrictions.between("dateOfBirth", atStartOfDay(date), atEndOfDay(date)));
}
persons = personService.searchByExpression(expressions);
return new ResponseEntity<List<Person>>(persons, null, HttpStatus.OK);
} catch (Exception e) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("Exception", e.getMessage());
ResponseEntity<List<Person>> respond = new ResponseEntity<List<Person>>(null, httpHeaders,
HttpStatus.INTERNAL_SERVER_ERROR);
return respond;
}
}
}
谁能帮我找出代码中出了什么问题吗?
最佳答案
这是以 @OneToMany
关系从数据库检索数据的默认策略,首次访问数据时应延迟获取数据,在这种情况下,您正在尝试序列化实体 session 结束后。尝试为此属性建立 EAGER
获取策略(有关详细信息,请查看 this):
@OneToMany(fetch = FetchType.EAGER, mappedBy="person")
private List<PersonOtherName> otherNames;
或者,您可以在关闭 session 之前强制此特定服务的代理初始化:
Hibernate.initialize(person.getOtherNames());
<小时/>
If you don't need to show this data in the interface, a more efficient solution would be not even serialize them:
@JsonIgnore
@OneToMany(mappedBy="person")
private List<PersonOtherName> otherNames;
关于java - 无法写入 JSON : failed to lazily initialize a collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50642258/
是否有带有索引的.collect?我想做这样的事情: def myList = [ [position: 0, name: 'Bob'], [position: 0, name: 'J
我创建了一个 Collection 类,它扩展了 ArrayList 以添加一些有用的方法。它看起来像这样: public class Collection extends ArrayList {
我知道如果我有元素,我想得到 List/Set/Map 我可以调用这个元素: Collections.singleton()/Collections.singletonList()/Collectio
我刚刚在我的 pom 文件中看到 Apache commons-collections 有两个不同的组 ID: commons-collections commons-collect
我们可以对所有 Collections 类型的对象(如 Set 和 List)使用 Collections.synchronizedCollection(Collection c),这就是为什么我们有
我有List>我想让它把上一个集合中的所有人复制到List收藏。 我是这样做的: var People = new List>{ new List{...},... };
我想做的是使用良好的旧循环非常简单。 假设我有一个包含 B 列表的对象 A。 public class A { public List myListOfB; } 在其他一些方法中,我有一个 As
在 Capgemini 的采访中,我被问到一个我无法回答的问题。所有集合类和接口(interface)共有的那些方法是什么? 最佳答案 所有 java 对象类(包括所有集合)都派生自名为 Object
我有一系列存储估计信息的数据库表。当设置某些边界时,我试图从所有数据库表中返回所有数据。 收藏 $estimateItems = new Collection(); $esti
为什么 Haskell 实现如此专注于链表? 例如,我知道 Data.Sequence 效率更高 大多数列表操作(cons 操作除外),并且被大量使用; 但是,从语法上讲,它“几乎不受支持”。 Has
我试图简单地将我在 PHP 中请求的内容返回到 JSON。我的问题是每个库存尚未完成。事实上,它是“渲染”,但“this.collection.models”尚未完成,因为请求尚未完成。 我应该如何解
本质上,作为Powershell脚本的一部分,我需要实现广度优先搜索。因此,我需要队列,并且认为System.Collections.Queue与其他任何队列一样好。但是,当我从队列中取出一个对象时,
已关闭。这个问题是 off-topic 。目前不接受答案。 想要改进这个问题吗? Update the question所以它是 on-topic用于堆栈溢出。 已关闭10 年前。 Improve t
嗨,我不明白为什么这不起作用? Notifications.update({'userId':Meteor.userId(), 'notifyUserId':notifyFriendId}, {$se
假设我有一个闭包: def increment = {value, step -> value + step } 现在我想遍历我的整数集合的每个项目,用 5 递增,并将新元素保存到一个新集合中:
使用逐页 View 时,我的 plone 集合文件夹未显示所有项目。基本上我有 9 页包含元素,但第 6 - 8 页显示的内容完全相同。因此,并非所有项目都会显示,即使项目总数对应于应该在集合中的元素
private Map> map ,其中 ProgramCourse 是我的项目中的域类,上面的 map 是我运行项目时域类 Program 的字段以下异常即将到来。 Use of @OneToMan
三者的主要区别是什么?现在,我想分别使用字符串/字符串创建一个键/值对。这三个似乎都有我可以使用的选项。 编辑:我只想创建一个简单的哈希表 - 没什么特别复杂的。 最佳答案 通用集合几乎完全取代了基础
我正在为 NodeJs 使用 mongodb 驱动程序,其中有 3 个方法: 1) db.collection.insert 2) 数据库.collection.insertOne 3) db.col
我有一个集合,我正在尝试使用 Distinct 方法删除重复项。 public static Collection imagePlaylist imagePlaylist = imagePlaylis
我是一名优秀的程序员,十分优秀!