2

I want to add database and persist data using JPA/hibernate. I've persistence.xml in right place but I'm getting "no persistence provider for entitymanager" error. Database is in mysql. Any suggestion is much appreciated. Here is my code:

Folder structure:

enter image description here

servlet:

@WebServlet("/Reservations")
public class Reservations extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            if( request != null) {

                Enumeration<String> names = request.getParameterNames();
                while(names.hasMoreElements()) {
                    String name = names.nextElement();
                    System.out.println(name + " : " + request.getParameter(name));
                }

                String pickUpDate = request.getParameter("pickUpDate");
                Integer totalPass = Integer.parseInt(request.getParameter("totalPass"));                

                ReservationEntity reservation = new ReservationEntity(pickUpDate, totalPass);
                ReservationSevice reservationSevice = new ReservationSevice();
                reservationSevice.createReservation(reservation);
            }else{
                System.out.println("#############Request is null#########");
            }
        }
        catch (Exception e){
            e.printStackTrace();
            System.out.println("Exception occured");
        }
    }
}

Entity class:

@Entity
@Table(name = "reservations_db")
public class ReservationEntity {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id; 
    @Column(name = "pickUpDate")
    private String pickUpDate;

    @Column(name = "totalPass")
    private Integer totalPass;

    public ReservationEntity() 
    {       
    }

    public ReservationEntity(String pickUpDate, Integer totalPass) 
    {
        this.setPickUpDate(pickUpDate);
        this.setTotalPass(totalPass);

    }

    public int getId() {
    return id;
}

 public void setId(int id) {
    this.id = id;
}
    public String getPickUpDate() {
        return pickUpDate;
    }
    public void setPickUpDate(String pickUpDate) {
        this.pickUpDate = pickUpDate;
    }

    public Integer getTotalPass() {
        return totalPass;
    }
    public void setTotalPass(Integer totalPass) {
        this.totalPass = totalPass;
    }
}

Service class for JPA persistence:

public class ReservationSevice 
{
    static EntityManagerFactory emf = Persistence.createEntityManagerFactory("ReservationsPU");
    private static EntityManager em = emf.createEntityManager(); 

    public void createReservation (ReservationEntity reservation)
    {
        em.getTransaction().begin();
        em.persist(reservation);
        em.getTransaction().commit();
    }
}

persistence.xml:

<persistence version="2.1"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="ReservationsPU">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/world" />
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
            <property name="hibernate.connection.username" value="root" />
            <property name="hibernate.connection.password" value="password" />
            <property name="hibernate.archive.autodetection" value="class" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <property name="hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>
</persistence>

error:

javax.persistence.PersistenceException: No Persistence provider for EntityManager named ReservationsPU
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
    at com.welcomelimo.service.ReservationSevice.<init>(ReservationSevice.java:11)
    at com.welcomelimo.controller.Reservations.doPost(Reservations.java:56)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2508)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2497)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Exception occured

Update

I'm adding the lib folder in order to show the jar files I've added for the project, since I'm not using maven.

enter image description here

Update 2

I ended up using maven and it's working now. For pom.xml, see below @Surace's answer.

JoeZ
  • 79
  • 1
  • 2
  • 11
  • 1
    Btw your entity should have an id. – Mordechai Dec 09 '16 at 01:56
  • @ MouseEvent , I've an id. I updated the question – JoeZ Dec 09 '16 at 02:01
  • @Scary Wombat, according to JPA doc, I need to add just persistence.xml where I configure persistence unit. I didn;t see anything about web.xml. Are you saying I've to add configuration in web.xml as well? – JoeZ Dec 09 '16 at 02:06
  • @JoeZ I am not sure myself, hence the comment – Scary Wombat Dec 09 '16 at 02:09
  • As per you updated question, what is the **build error** in eclipse – Scary Wombat Dec 09 '16 at 02:30
  • @scary-wombat, the same build error – JoeZ Dec 09 '16 at 02:45
  • Have you checked http://stackoverflow.com/questions/1158159/no-persistence-provider-for-entitymanager-named – Scary Wombat Dec 09 '16 at 02:51
  • Are you sure `persistence.xml` is really in the final WAR? I believe putting it in `src/META-INF/persistence.xml` may not be a proper place to get it properly included – Adrian Shum Dec 09 '16 at 03:01
  • @AdrianShum, JPA doc says, https://docs.oracle.com/cd/E19798-01/821-1841/bnbrj/index.html . So, src as root is an option. But, how can I check the final war file in eclipse? I gave my project folder structure in eclipse in the question. Thanks. – JoeZ Dec 09 '16 at 14:03
  • I cannot see any place in the JPA spec saying you can put the things under `src/` – Adrian Shum Dec 12 '16 at 10:32

2 Answers2

4

Change your persistence.xml to

<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="ReservationsPU">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/world" />
        <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
        <property name="hibernate.connection.username" value="root" />
        <property name="hibernate.connection.password" value="password" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
        <property name="hibernate.hbm2ddl.auto" value="create" />
        <property name="hibernate.show_sql" value="true" />
        <property name="use_sql_comments" value="true" />
        <property name="hibernate.format_sql" value="true" />
    </properties>
</persistence-unit>

Add following dependencies in your pom.xml if you are using Maven

<dependencies>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.1-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.37</version>
    </dependency>

</dependencies>
Suresh A
  • 1,178
  • 2
  • 10
  • 21
  • I wanna use JPA 2.1 version, that's why I used this provider. But I tried your one as well, same error. For some reason, it's not getting persistence.xml configuration. I followed all the steps according to Jpa doc. – JoeZ Dec 09 '16 at 02:48
  • You should also add dependencies in your pom.xml. – Suresh A Dec 09 '16 at 02:59
  • May be I have missed but I cannot see OP mentioning that he is using Maven. I believe it is better to mention `hibernate-entitymanager.jar` should be in classpath, and use pom.xml as example if he is using Maven – Adrian Shum Dec 09 '16 at 03:04
  • Actually I believe quite possibly that OP is NOT using Maven, based on the directory structure he showed – Adrian Shum Dec 09 '16 at 03:05
  • Yes @AdrianShum you are right he is not using Maven. Joez have you tried above answer? Do you have jar in your library folder? – Suresh A Dec 09 '16 at 03:11
  • @Surace, I tried your answer by changing the provider name and putting hibernate.hbm2ddl.auto value as "create", but no luck. Same error. – JoeZ Dec 09 '16 at 14:14
  • @Surace, I'm adding the library folder in the question as an update. – JoeZ Dec 09 '16 at 14:15
  • It works in my machine . But i test it in Maven project. – Suresh A Dec 09 '16 at 15:02
  • @Surace, can you put the pom.xml file? I would like to use maven. Thanks. – JoeZ Dec 09 '16 at 16:53
  • Please update your question and tell you are using maven otherwise others will confuse . – Suresh A Dec 09 '16 at 23:00
0

I think the matter is with eclipse. Eclipse may only allow running JPA if it is explicitly set as a JPA project.

You can convert your project into a JPA project, by opening the context menu in the explorer.

Mordechai
  • 15,437
  • 2
  • 41
  • 82