JPA:在独立的Java应用程序中保留后如何获取ID [英] JPA: How to get Id after persist in standalone java app
问题描述
这是一个独立的Java应用程序,而不是Web应用程序.所以当我坚持这样的对象
This is a standalone java application, not web application. So when I persist the object like this
public <T> T create(T t) {
em.getTransaction().begin();
em.persist(t);
em.flush();
em.getTransaction().commit();
return t;
}
即使在数据库内部正确创建了具有正确数据和ID的新行,T t
对象内部的id
仍然为空.通常在使用@EJB
的Web应用程序中,id
在我持久化之后立即可用,因为它会将实体对象持久化到我的持久化上下文中,所以我不确定我是否在这里有我的持久化上下文?
The id
inside the T t
object is still null, even though a new row with correct data and id is created correctly inside the database. Usually in my web app that utilize @EJB
, the id
available right after I persist, since it persist the entity object into my persistence context, I am not sure if I have my persistence context here?
这就是我将ID映射到@Entity类中的方式
This is how I mapped my id inside my @Entity Class
@Id
@Basic(optional = false)
@Column(name = "ID")
private Long id;
我也像这样在数据库AUTO_INCREMENT
中创建该表的ID
also I make the id of this table in the database AUTO_INCREMENT
, like this
CREATE TABLE Config
(
ID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY (ID)
)
这就是我获取EntityManager的方式
This is how I obtain my EntityManager
EntityManagerFactory emf = Persistence.createEntityManagerFactory("CorePU");
em = emf.createEntityManager();
这是我的persistence.xml
<persistence-unit name="CorePU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.wf.docsys.core.model.Config</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/XNINFODB"/>
<property name="javax.persistence.jdbc.password" value="xxx"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="xxx"/>
</properties>
请帮助,我不确定我在这里做错了什么.
Please help, I am not sure what I did wrong here.
推荐答案
这是我的答案.经过测试
映射您的ID时,请从上面的内容中切换
When mapping your Id, switch from what I have above, which is
@Id
@Basic(optional = false)
@Column(name = "ID")
private Long id;
到
@Entity
public class Person {
@Id
@TableGenerator(name="TABLE_GEN", table="SEQUENCE_TABLE", pkColumnName="SEQ_NAME",
valueColumnName="SEQ_COUNT", pkColumnValue="PERSON_SEQ")
@GeneratedValue(strategy=GenerationType.TABLE, generator="TABLE_GEN")
private long id;
...
}
由于我使用Microsoft SQL Server,因此必须使用@TableGenerator
.可在此处找到更多信息 http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing #Table_sequencing
Since I use microsoft SQL server, I have to use @TableGenerator
. More information can be found here http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Table_sequencing
这篇关于JPA:在独立的Java应用程序中保留后如何获取ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!