【发布时间】:2016-03-16 22:50:13
【问题描述】:
在我对 JPA 的探索中,我有下面的代码(我理解不应该在生产中使用)。运行我的代码会产生以下错误:
java.lang.IllegalStateException:
Exception Description: Cannot use an EntityTransaction while using JTA.
资源代码如下:
@Path("users")
public class UsersAPI {
@Context
UriInfo uriInfo;
@Inject
UserBean accountsBean;
@GET
@Path("deduplicate")
public Response deduplicateDB(){
List<UserProfile> profiles = accountsBean.getAll();
int profilesNum = profiles.size();
for(int i = 0; i < profilesNum; ++i){
for(int k = 0; k < profilesNum; ++k){
if(i != k){ //if it's not the same profile
if(profiles.get(i).getUsername().equals(profiles.get(k).getUsername())){
accountsBean.remove(profiles.get(k));
profiles.remove(k);
}
}
profilesNum = profiles.size();
}
}
return Response.ok().build();
}
}
ProfilesBean中的代码如下:
@Local
@Stateless
public class UserBean {
@PersistenceContext
EntityManager eManager;
public void save(UserProfile data){
eManager.merge(data);
}
public void remove(UserProfile data){
eManager.getTransaction().begin();
eManager.remove(data);
eManager.getTransaction().commit();
}
public List<UserProfile> getAll(){
Query q = eManager.createQuery("SELECT profile FROM Users profile");
return (List<UserProfile>)q.getResultList();
}
}
这里是实体类的代码:
@Entity(name="Users")
public class UserProfile {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
Long id;
String password;
@Column(unique=true)
String username;
public UserProfile(String username){
setUsername(username);
}
public UserProfile(){
this(null);
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
似乎错误来自我以某种方式滥用平台。我怎样才能修复此代码并且以后不会滥用该平台?
【问题讨论】:
标签: jax-rs jpa-2.1 glassfish-4.1 jakarta-ee