我有以下简单的 web 服务声明为@Stateless
在 GlassFish 3.1.2.2 上运行的 EJB,并使用 EclipseLink 2.4.1 使用 JTADataSource
连接到 MySQL 数据库:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response update(TimeRow e) throws Exception {
if ((e.getKey() == null) || !e.getKey().keyValid()) {
return Response.status(400).build();
}
TimeRow existing = em.find(TimeRow.class, e.getKey());
if (existing == null) {
em.persist(e);
} else {
existing.setValues(e.getValues());
em.flush();
}
return Response.status(204).build();
}
实体类TimeRow
:
@Entity
@NamedQueries({
@NamedQuery(name="TimeRow.findAllByUser",
query="SELECT t FROM TimeRow t WHERE t.table.userId = :uid")
})
public class TimeRow implements Serializable {
@EmbeddedId
private TimeRowPK key;
@MapsId("userId")
@JoinColumn(name = "USERID", referencedColumnName = "userId")
@ManyToOne
private UserTable table;
@Column(name="ROWVALUES")
private List<Double> values;
public TimeRow() {
this.key = new TimeRowPK();
this.values = new ArrayList<Double>(20);
extendValuesTo20();
}
public TimeRow(String uid, Date date) {
this.key = new TimeRowPK(date, uid);
this.table = new UserTable(uid);
this.values = new ArrayList<Double>(20);
extendValuesTo20();
}
public List<Double> getValues() {
return values;
}
public void setValues(List<Double> values) {
this.values = values;
extendValuesTo20();
}
private void extendValuesTo20() {
if (this.values.size() < 20) {
for (int i = this.values.size(); i < 20; i++) {
this.values.add(0.0);
}
}
}
}
@EmbeddableId
TimeRowPK
:
@Embeddable
public class TimeRowPK implements Serializable {
public TimeRowPK() { }
public TimeRowPK(Date date, String userId) {
this.date = date;
this.userId = userId;
}
@Column(name="DAY")
private Date date;
@Column(name = "USERID")
private String userId;
public boolean keyValid() {
return ((date != null) && ((userId != null) && !userId.isEmpty()));
}
}
persistence.xml
(不带<persistence>
标签):
<persistence-unit name="test" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/test</jta-data-source>
<class>com.test.TimeRow</class>
<class>com.test.TimeRowPK</class>
<class>...</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
网络服务声明:
@Path("row")
@Stateless
public class TimeRowWebService {
@PersistenceContext(unitName = "test")
private EntityManager em;
...
}
问题是,如果实体存在,则更改仅存储在 中PersistenceContext
,但不会提交到数据库。这意味着我可以通过更改检索正确的数据,但是例如,如果我重新启动 AS,更改就消失了。AS 日志中没有错误。
所以我想我必须做一些 bean 级别的手动事务处理才能完成这项工作。我必须添加什么才能使其正常工作?