I'm trying to save entity to DB using jpa. Here is my Entity:
import javax.persistence.*;
@Entity
public class Book {
@Id
@GeneratedValue
private Long id;
private String title;
public Book() {
}
public Book(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Here persistence.xml:
<persistence-unit name="bookUnit">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>ee.jpa.Book</class>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/Lessons"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="1"/>
</properties>
</persistence-unit>
Here is my EJB:
@Stateless
public class JpaBean {
@PersistenceContext
EntityManager entityManager;
public long saveBook(Book book) {
entityManager.persist(book);
return book.getId();
}
}
Here is my servlet:
@WebServlet("/jpaExample")
public class ServletExample extends HttpServlet {
@EJB
JpaBean jpaBean;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Book book = new Book("servlet");
long l = jpaBean.saveBook(book);
resp.getWriter().write(l + " ");
}
}
I've added EclipseLink.jar to my project and to TomcatEEDir/lib/ directory. Everything compiles and run with no exception. I get different numbers each time I run servlet, like 1 2 3.... etc. But when I look at db there nothing there. No table, no data. What I did wrong? How to fix it? Also I tried to use java SE, for this I added transaction-type="RESOURCE_LOCAL" to persistence-unit. And wrote code like this:
public class MainExample {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("bookUnit");
EntityManager em = emf.createEntityManager();
Book book = new Book("main");
EntityTransaction tx = em.getTransaction();
tx.begin();
em.persist(book);
tx.commit();
em.close();
emf.close();
}
}
This code works perfectly and saves data to DB. So, what is wrong with my previous code. Why nothing saves to DB?
Edit: Same result if using Hibernate.