Reputation: 265
I am trying to persist an entity. When I use a native query to insert a row to my table it works fine, but when I use the EntityManager persist method to insert the entity I get an error complaining about the query as if it is syntactically wrong.
Bellow is my entity class:
import javax.persistence.*;
import java.util.Date;
@Entity
public class Media {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "media_location")
private String mediaLocation;
@Column(name = "media_location_url")
private boolean fromUrl = false;
@Column(name = "date")
private Date uploadDate;
@Column(name = "description")
private String description;
public Media() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMediaLocation() {
return mediaLocation;
}
public void setMediaLocation(String mediaLocation) {
this.mediaLocation = mediaLocation;
}
public boolean isFromUrl() {
return fromUrl;
}
public void setFromUrl(boolean fromUrl) {
this.fromUrl = fromUrl;
}
public Date getUploadDate() {
return uploadDate;
}
public void setUploadDate(Date uploadDate) {
this.uploadDate = uploadDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I have my manager class as bellow:
@Stateless
public class UserManager {
@EJB
private BaseDao baseDao;
public String createNewMedia_test() {
Media media = new Media();
media.setFromUrl(false);
media.setDescription("adsddfsd");
media.setMediaLocation("here");
media.setUploadDate(new Date());
baseDao.saveMedia(media);
return "OK";
}
}
And BaseDao is as bellow :
@Stateless
public class BaseDao {
@PersistenceContext(unitName="MySqlDS")
private EntityManager entityManager;
public void saveMedia(Media media) {
entityManager.persist(media);
}
}
But it's upon the persist call that I get the error, in my localhost web ui I see the stack trace starting with
Query String:null
Stack Trace
javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Upvotes: 2
Views: 2093
Reputation: 521249
I believe you need to call persist()
within a Hibernate transaction. Try wrapping your call to persist()
inside a transaction as in the following code snippet:
@Stateless
public class BaseDao {
@PersistenceContext(unitName="MySqlDS")
private EntityManager entityManager;
public void saveMedia(Media media) {
entityManager.getTransaction().begin();
entityManager.persist(media);
entityManager.getTransaction().commit();
}
}
Upvotes: 1