Java有transient关键字.为什么JPA @Transient不是简单地使用已经存在的java关键字?
我有一个简单的控制器返回一个User对象,这个用户的属性坐标有hibernate属性FetchType.LAZY.
当我尝试获取此用户时,我总是必须加载所有坐标以获取用户对象,否则当Jackson尝试序列化时,用户会抛出异常:
com.fasterxml.jackson.databind.JsonMappingException:无法初始化代理 - 没有会话
这是因为杰克逊试图获取这个未被攻击的对象.这是对象:
public class User{
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
@JsonManagedReference("user-coordinate")
private List<Coordinate> coordinates;
}
public class Coordinate {
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
@JsonBackReference("user-coordinate")
private User user;
}
Run Code Online (Sandbox Code Playgroud)
和控制器:
@RequestMapping(value = "/user/{username}", method=RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String username) {
User user = userService.getUser(username);
return user;
}
Run Code Online (Sandbox Code Playgroud)
有办法告诉杰克逊不要序列化未被攻击的物体吗?我一直在寻找3年前发布的其他答案实现jackson-hibernate-module.但可能通过新的杰克逊功能可以实现.
我的版本是:
提前致谢.
我正在使用spring-boot来提供与MongoDB持久化的REST接口.我正在使用'标准'依赖关系来支持它,包括spring-boot-starter-data-mongodb和spring-boot-starter-web.
但是,在我的一些类中,我有一些注释的字段,@Transient以便MongoDB不会保留该信息.但是,我希望这些信息在我的休息服务中发送出去.不幸的是,MongoDB和其他控制器似乎都共享该注释.因此,当我的前端收到JSON对象时,这些字段不会被实例化(但仍然被声明).删除注释允许字段在JSON对象中通过.
我如何分别为MongoDB和REST配置瞬态?
这是我的课
package com.clashalytics.domain.building;
import com.clashalytics.domain.building.constants.BuildingConstants;
import com.clashalytics.domain.building.constants.BuildingType;
import com.google.common.base.Objects;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import java.util.*;
public class Building {
@Id
private int id;
private BuildingType buildingType;
private int level;
private Location location;
// TODO http://stackoverflow.com/questions/30970717/specify-field-is-transient-for-mongodb-but-not-for-restcontroller
@Transient
private int hp;
@Transient
private BuildingDefense defenses;
private static Map<Building,Building> buildings = new HashMap<>();
public Building(){}
public Building(BuildingType buildingType, int level){
this.buildingType = buildingType;
this.level = level;
if(BuildingConstants.hpMap.containsKey(buildingType))
this.hp = BuildingConstants.hpMap.get(buildingType).get(level - 1);
this.defenses = …Run Code Online (Sandbox Code Playgroud) 我有一个域类 Loan.java 有一个不持久的字段:
@JsonInclude()
@Transient
private LoanRating loanRating;
/* (Public) Getters and setters for that field are available as well */
Run Code Online (Sandbox Code Playgroud)
但是,该字段没有被序列化 - 我在前端没有看到它。我正在和杰克逊一起做序列化。
任何想法我做错了什么?
如果您需要更多信息,请告诉我,我会发布其他代码:)
我有一个实体,调用Users了login,name和department作为存储在Users表中的字段.
我的Spring-Boot配置定义了为此应用程序中的用户提供系统管理员角色的部门.
关键问题是我希望登录end-point返回用户数据以及他/她是或不是系统管理员的附加信息.
我认为这些信息应该在User类中,但是我不希望这些信息与其他字段一起存储在数据库中,因为管理部门可能会更改,或者用户将我从一个部门更改为另一个部门而不管理系统.
(编辑)我将在用户请求login()时定义此IsManager字段:我将获取用户的department字段并检查其managerDepartment列表以将其设置为true ou false.
所以问题是将信息放在实体类中的非持久字段中(以及如何做)或者如果我可以在rest方法中更改ResponseEntity以添加其他信息(以及如何),是否正确?