3

非エンティティ オブジェクトの同じインスタンスをデータベースに永続化せずに JPA エンティティに格納する必要があるプレイ フレームワークでアプリケーションを実行しています。それを達成できるかどうか、またはアノテーションを使用しないかどうかを知りたいです。私が探しているもののサンプルコードは次のとおりです。

 public class anEntity extends Model {
    @ManyToOne
    public User user;

    @ManyToOne
    public Question question;


    //Encrypted candidate name for the answer
    @Column(columnDefinition = "text")
    public BigInteger candidateName;

    //I want that field not to be inserted into the database
    TestObject p= new TestObject();

@Embedded アノテーションを試しましたが、オブジェクト フィールドをエンティティ テーブルに埋め込むことになっています。オブジェクト列をエンティティテーブルに隠したまま@Embeddedを使用する方法はありますか?

4

1 に答える 1

7

@Transientアノテーションを確認してください。

「この注釈は、プロパティまたはフィールドが永続的でないことを指定します。エンティティ クラス、マップされたスーパークラス、または埋め込み可能なクラスのプロパティまたはフィールドに注釈を付けるために使用されます。」

常に同じオブジェクトを確実に取得するには、Singletonパターンを実装して、エンティティがそのgetInstance()メソッドを使用して一時オブジェクトを設定できるようにします。

したがって、これでうまくいくはずです:

public class anEntity extends Model {
    @Transient
    private TransientSingleton t;

    public anEntity(){ // JPA calls this so you can use the constructor to set the transient instance.
        super();
        t=TransientSingleton.getInstance();
    }


public class TransientSingleton { // simple unsecure singleton from wikipedia

    private static final TransientSingleton INSTANCE = new TransientSingleton();
    private TransientSingleton() {
        [...do stuff..]
    }
    public static TransientSingleton getInstance() {
        return INSTANCE;
    }
}
于 2011-05-09T18:50:43.090 に答える