我实际上是在寻找一个“@Ignore”类型的注释,我可以用它来停止某个特定字段的持久化。如何实现这一目标?
当前回答
使用@Transient使JPA忽略字段。
但是!Jackson也不会序列化该字段。要解决这个问题,只需添加@JsonProperty
一个例子
@Transient
@JsonProperty
private boolean locked;
其他回答
显然,使用Hibernate5Module时,如果使用ObjectMapper, @Transient将不会被序列化。移除会让它起作用。
import javax.persistence.Transient;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TransientFieldTest {
@Test
public void Print_Json() throws JsonProcessingException {
ObjectMapper objectEntityMapper = new ObjectMapper();
//objectEntityMapper.registerModule(new Hibernate5Module());
objectEntityMapper.setSerializationInclusion(Include.NON_NULL);
log.info("object: {}", objectEntityMapper.writeValueAsString( //
SampleTransient.builder()
.id("id")
.transientField("transientField")
.build()));
}
@Getter
@Setter
@Builder
private static class SampleTransient {
private String id;
@Transient
private String transientField;
private String nullField;
}
}
None of the above answers worked for me using Hibernate 5.2.10, Jersey 2.25.1 and Jackson 2.8.9. I finally found the answer (sort of, they reference hibernate4module but it works for 5 too) here. None of the Json annotations worked at all with @Transient. Apparently Jackson2 is 'smart' enough to kindly ignore stuff marked with @Transient unless you explicitly tell it not to. The key was to add the hibernate5 module (which I was using to deal with other Hibernate annotations) and disable the USE_TRANSIENT_ANNOTATION feature in my Jersey Application:
ObjectMapper jacksonObjectMapper = new ObjectMapper();
Hibernate5Module jacksonHibernateModule = new Hibernate5Module();
jacksonHibernateModule.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
jacksonObjectMapper.registerModule(jacksonHibernateModule);
下面是Hibernate5Module的依赖:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.8.9</version>
</dependency>
这个回答来的有点晚,但它完成了响应。
为了避免来自实体的字段被持久化到DB中,可以使用以下两种机制之一:
@Transient—标记字段不可持久的JPA注释
java中的Transient关键字。注意-使用此关键字将阻止该字段与java中的任何序列化机制一起使用。因此,如果字段必须序列化,最好只使用@Transient注释。
要忽略一个字段,请使用@Transient注释它,这样它就不会被hibernate映射。 来源:Hibernate注解。
为了完成上面的回答,我使用了一个XML映射文件,其中@Transient和transient都不工作… 我必须把临时信息放在xml文件中:
<attributes>
(...)
<transient name="field" />
</attributes>
推荐文章
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 为什么我应该使用基于文档的数据库而不是关系数据库?
- 应该……接住环内还是环外?
- 哪个更快/最好?SELECT *或SELECT columnn1, colum2, column3等