JPA toplink-essentialとSQL Server 2008を使用しています
私の目標は、テーブルに挿入されるデータの自動インクリメント主キー値を取得することです。JDBCでは、自動インクリメントプライマリIDのIDを提供するgetInsertedId()のようなメソッドがあります(ただし、insertステートメントが実行された後です)
JPAで、私@GenratedValue annotation
はそのトリックを行うことができることを発見しました。
@Entity
@Table(name = "tableOne")
public class TableOne implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "tableId")
private Integer tableId;
以下のコードを実行すると、自動インクリメントされたIDが返されますが、NULLが返されます...
EntityManager em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager();
EntityTransaction txn = em.getTransaction();
txn.begin();
TableOne parent = new TableOne();
em.persist(parent); //here I assume that id is pre-generated for me.
System.out.println(parent.getTableId()); //this returns NULL :(