实体 JPA 中的会话范围 属性

Session scoped property in an entity 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,但在会话关闭时将其重置。我是在market视图中计算的,想在caddy视图中得到这个信息。现在,即使我断开连接并重新连接到另一个帐户,这个值也保持不变。

要使 属性 成为会话作用域,它需要是一个 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());