java - 实体 JPA 中的会话范围属性
问题描述
我对 JPA 很陌生。我的问题是:是否可以在未保存在数据库中但为 SessionScoped 的实体中定义属性?
@Entity
@Table(name = "article_v_m")
public class Article implements Serializable {
@Id
@Column(name = "cart")
private String ref;
@Transient
public static final List<String> STATUS_PUBLISHED = Collections.unmodifiableList(Arrays.asList("", "D", "R"));
@Transient
public static final List<String> STATUS_DEAD = Collections.unmodifiableList(Arrays.asList("M", "E", "V"));
@Transient
public static final List<String> STATUS_UPCOMING = Collections.unmodifiableList(Arrays.asList("A"));
// I want this property to be SessionScoped
// The problem is that it persists between sessions
// I know this is because of the @Transient annotation
@Transient
public Double realDiscountPercent = 0.00;
@Column(name = "isbn")
private String isbn;
@Column(name = "lart")
private String title;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
if (fullTitle == null || fullTitle.isEmpty()) {
return title;
}
return fullTitle;
}
public void setTitle(String title) {
this.title = title;
}
public Double getRealDiscountPercent() {
return realDiscountPercent;
}
public void setRealDiscountPercent(Double realDiscountPercent) {
this.realDiscountPercent = realDiscountPercent;
}
}
目的是在视图之间检索 realDiscountPercent,但在会话关闭时将其重置。我在市场视图中计算它,并希望在球童视图中获取此信息。现在,即使我断开连接并重新连接到另一个帐户,这个值也保持不变。
解决方案
对于会话范围的属性,它需要是一个singleton
bean,因此您可以创建一个,例如:
@Component
@Scope("session")
public class MyStringProvider implements Provider<String> {
private String value = "something";
public String get() {
return this.value;
}
}
然后你可以像这样访问它:
@Autowired
private Provider<String> myStringProvider;
...
System.out.println(myStringProvider.get());
推荐阅读
- python - Python:如何使用 UTF-8/Unicode 名称通过 Ftp 打开文件?
- reactjs - React-Native 使用 React Hooks 使 setInterval 声明性
- sql - SQL Server 完整外部组未获取所有值
- excel - 将带有循环的类型声明为变量
- mongodb - 忽略 MongoDB 中聚合操作中的 NULL 值
- regex - 字符串到数组或哈希表
- python - 检测图像中线的起点和终点(numpy数组)
- java - 如果子类中未定义父构造函数,子类是否使用父构造函数?
- javascript - TinyMCE 5 color_map 设置不显示自定义颜色
- javascript - angularjs中基于条件的显示数据