Java Persistence API (JPA) TutorialsFree and quality Java programming tutorials, articles, guides, code examples, sample projects and best practiceshttps://codejava.net/java-ee/jpa2024-05-11T16:50:42-05:00Joomla! - Open Source Content ManagementJPA Named Query Examples2018-06-25T20:10:13-05:002018-06-25T20:10:13-05:00https://codejava.net/java-ee/jpa/jpa-named-query-examplesNam Ha Minhhainatu@gmail.com<div class="feed-description"><p>This tutorial guides you how to use named queries in Java Persistence API (JPA). Basically you execute a query in JPA like this:</p>
<pre class="brush:java">String jpql = "SELECT u from User u";
Query query = entityManager.createQuery(jpql);
List<User> result = query.getResultList();
for (User user : result) {
System.out.println(user);
}</pre>
<p>This approach is perfect for simple applications that have only a small number of queries. What if your application becomes larger with tens or hundreds queries scattered in many classes? Then imagine the nightmare of maintaining such a large number of queries in your fat code base. Therefore, JPA provides the concept of named queries to make programmer’s life easier: you can group related queries in one place (usually in model classes) and refer them in your code by their names - hence the term named queries. Below is an example:</p>
<pre class="brush:java">String queryName = "User.findAll";
Query query = entityManager.createNamedQuery(queryName);
List<User> listUsers = query.getResultList();
</pre>
<p>Here, the query name “<span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">User.findAll</span>” refers to a query which can be stored in a relevant domain model class like this:</p>
<pre class="brush:java; highlight: [4,6]">@Entity
@Table(name = "USERS")
@NamedQueries({
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u ORDER BY u.fullname")
})
public class User {
private Integer id;
private String fullname;
private String email;
private String password;
...
...
}</pre>
<p>As you can see, there are two annotations are used for named query:<span style="color: #800000;"> <strong><span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';">@NamedQueries</span></strong></span> annotation consists of a set of <span style="color: #800000;"><strong><span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';">@NameQuery</span></strong></span> annotations with each define a specific JPQL query:</p>
<pre class="brush:java">@NamedQueries({
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u ORDER BY u.fullname")
})</pre>
<p>To specify multiple named queries, separate the <span style="color: #800000;"><strong><span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';">@NameQuery</span></strong></span> annotations by commas:</p>
<pre class="brush:java">@NamedQueries({
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u ORDER BY u.fullname"),
@NamedQuery(name = "User.count", query = "SELECT COUNT(*) FROM User u"),
@NamedQuery(name = "User.removeAll", query = "DELETE FROM User u")
})</pre>
<p> </p>
<p>The following code illustrates how to execute the named query <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">User.count</span> above:</p>
<pre class="brush:java">Query query = entityManager.createNamedQuery("User.count");
long count = (long) query.getSingleResult();</pre>
<p> </p>
<p>And the following example executes the named query <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">User.removeAll</span> above:</p>
<pre class="brush:java">entityManager.getTransaction().begin();
Query query = entityManager.createNamedQuery("User.removeAll");
query.executeUpdate();
entityManager.getTransaction().commit();</pre>
<p> </p>
<h2><span style="font-size: 16pt; line-height: 115%;">Using Named Query with Parameters:</span></h2>
<p>If your query consists of parameters, you can use the <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;"><strong>setParameter</strong>(name, value)</span> or <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;"><strong>setParameter</strong>(position, value) </span>to set values for the parameters dynamically.</p>
<p>For example, consider the following named query that contains one parameter named <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';">email</span>: </p>
<pre class="brush:java">@NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email")</pre>
<p> </p>
<p>The following code sets parameter for this query and executes it (set values for parameters by their names):</p>
<pre class="brush:java">String queryName = "User.findByEmail";
String email = "tom@gmail.com";
Query query = entityManager.createNamedQuery(queryName);
query.setParameter("email", email);
User user = (User) query.getSingleResult();</pre>
<p> </p>
<p>And this named query has two positional parameters:</p>
<pre class="brush:java">@NamedQuery(name = "User.checkLogin", query = "SELECT u FROM User u WHERE u.email = ?1 AND password = ?2")</pre>
<p> </p>
<p>And the following code sets values for the positional parameters above:</p>
<pre class="brush:xml; highlight: [5,6,7]">String queryName = "User.checkLogin";
String email = "tom@gmail.com";
String pass = "tomsecret1";
Query query = entityManager.createNamedQuery(queryName);
query.setParameter(1, email);
query.setParameter(2, pass);
User user = (User) query.getSingleResult();</pre>
<p>It’s recommended to use name-based parameters for the readability of your code.</p>
<p> </p>
<h2><span style="font-size: 16pt; line-height: 115%;">Named Queries Stored in XML:</span></h2>
<p>Besides embedding named queries in model classes, you can also store named queries in a separate XML file. For example, create <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">queries.xml</span> file under <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';"><span style="color: #800000;">META-INF</span> </span>directory with the following content:</p>
<pre class="brush:xml"><?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.0" xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_2_0.xsd "
>
<named-query name="WhoUsingGmail">
<query>SELECT u FROM User u WHERE u.email LIKE '%gmail%'</query>
</named-query>
<named-query name="WhoNotSetPassword">
<query>SELECT u FROM User u WHERE u.password is null</query>
</named-query>
</entity-mappings></pre>
<p> </p>
<p>And tell JPA to load this XML file in the <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">persistence.xml </span>file like this:</p>
<pre class="brush:xml">…
<persistence-unit name="UsersDB">
<mapping-file>META-INF/queries.xml</mapping-file>
<properties>
...
</properties>
</persistence-unit>
…</pre>
<p>Then you can use named queries in your code normally. This configuration is more flexible as we don’t have to re-compile the code when making changes to the queries.</p>
<p> </p>
<h3><span style="line-height: 115%;">References:</span></h3>
<p style="text-indent: 0.5in;"><a href="https://docs.oracle.com/javaee/7/api/javax/persistence/Query.html" rel="nofollow" target="_blank">Query Javadocs</a></p>
<p><span> </span><a href="https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html" rel="nofollow" target="_blank">EntityManager Javadocs</a></p></div><div class="feed-description"><p>This tutorial guides you how to use named queries in Java Persistence API (JPA). Basically you execute a query in JPA like this:</p>
<pre class="brush:java">String jpql = "SELECT u from User u";
Query query = entityManager.createQuery(jpql);
List<User> result = query.getResultList();
for (User user : result) {
System.out.println(user);
}</pre>
<p>This approach is perfect for simple applications that have only a small number of queries. What if your application becomes larger with tens or hundreds queries scattered in many classes? Then imagine the nightmare of maintaining such a large number of queries in your fat code base. Therefore, JPA provides the concept of named queries to make programmer’s life easier: you can group related queries in one place (usually in model classes) and refer them in your code by their names - hence the term named queries. Below is an example:</p>
<pre class="brush:java">String queryName = "User.findAll";
Query query = entityManager.createNamedQuery(queryName);
List<User> listUsers = query.getResultList();
</pre>
<p>Here, the query name “<span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">User.findAll</span>” refers to a query which can be stored in a relevant domain model class like this:</p>
<pre class="brush:java; highlight: [4,6]">@Entity
@Table(name = "USERS")
@NamedQueries({
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u ORDER BY u.fullname")
})
public class User {
private Integer id;
private String fullname;
private String email;
private String password;
...
...
}</pre>
<p>As you can see, there are two annotations are used for named query:<span style="color: #800000;"> <strong><span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';">@NamedQueries</span></strong></span> annotation consists of a set of <span style="color: #800000;"><strong><span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';">@NameQuery</span></strong></span> annotations with each define a specific JPQL query:</p>
<pre class="brush:java">@NamedQueries({
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u ORDER BY u.fullname")
})</pre>
<p>To specify multiple named queries, separate the <span style="color: #800000;"><strong><span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';">@NameQuery</span></strong></span> annotations by commas:</p>
<pre class="brush:java">@NamedQueries({
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u ORDER BY u.fullname"),
@NamedQuery(name = "User.count", query = "SELECT COUNT(*) FROM User u"),
@NamedQuery(name = "User.removeAll", query = "DELETE FROM User u")
})</pre>
<p> </p>
<p>The following code illustrates how to execute the named query <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">User.count</span> above:</p>
<pre class="brush:java">Query query = entityManager.createNamedQuery("User.count");
long count = (long) query.getSingleResult();</pre>
<p> </p>
<p>And the following example executes the named query <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">User.removeAll</span> above:</p>
<pre class="brush:java">entityManager.getTransaction().begin();
Query query = entityManager.createNamedQuery("User.removeAll");
query.executeUpdate();
entityManager.getTransaction().commit();</pre>
<p> </p>
<h2><span style="font-size: 16pt; line-height: 115%;">Using Named Query with Parameters:</span></h2>
<p>If your query consists of parameters, you can use the <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;"><strong>setParameter</strong>(name, value)</span> or <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;"><strong>setParameter</strong>(position, value) </span>to set values for the parameters dynamically.</p>
<p>For example, consider the following named query that contains one parameter named <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';">email</span>: </p>
<pre class="brush:java">@NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email")</pre>
<p> </p>
<p>The following code sets parameter for this query and executes it (set values for parameters by their names):</p>
<pre class="brush:java">String queryName = "User.findByEmail";
String email = "tom@gmail.com";
Query query = entityManager.createNamedQuery(queryName);
query.setParameter("email", email);
User user = (User) query.getSingleResult();</pre>
<p> </p>
<p>And this named query has two positional parameters:</p>
<pre class="brush:java">@NamedQuery(name = "User.checkLogin", query = "SELECT u FROM User u WHERE u.email = ?1 AND password = ?2")</pre>
<p> </p>
<p>And the following code sets values for the positional parameters above:</p>
<pre class="brush:xml; highlight: [5,6,7]">String queryName = "User.checkLogin";
String email = "tom@gmail.com";
String pass = "tomsecret1";
Query query = entityManager.createNamedQuery(queryName);
query.setParameter(1, email);
query.setParameter(2, pass);
User user = (User) query.getSingleResult();</pre>
<p>It’s recommended to use name-based parameters for the readability of your code.</p>
<p> </p>
<h2><span style="font-size: 16pt; line-height: 115%;">Named Queries Stored in XML:</span></h2>
<p>Besides embedding named queries in model classes, you can also store named queries in a separate XML file. For example, create <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">queries.xml</span> file under <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New';"><span style="color: #800000;">META-INF</span> </span>directory with the following content:</p>
<pre class="brush:xml"><?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="2.0" xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm
http://java.sun.com/xml/ns/persistence/orm_2_0.xsd "
>
<named-query name="WhoUsingGmail">
<query>SELECT u FROM User u WHERE u.email LIKE '%gmail%'</query>
</named-query>
<named-query name="WhoNotSetPassword">
<query>SELECT u FROM User u WHERE u.password is null</query>
</named-query>
</entity-mappings></pre>
<p> </p>
<p>And tell JPA to load this XML file in the <span style="font-size: 10pt; line-height: 115%; font-family: 'Courier New'; color: #800000;">persistence.xml </span>file like this:</p>
<pre class="brush:xml">…
<persistence-unit name="UsersDB">
<mapping-file>META-INF/queries.xml</mapping-file>
<properties>
...
</properties>
</persistence-unit>
…</pre>
<p>Then you can use named queries in your code normally. This configuration is more flexible as we don’t have to re-compile the code when making changes to the queries.</p>
<p> </p>
<h3><span style="line-height: 115%;">References:</span></h3>
<p style="text-indent: 0.5in;"><a href="https://docs.oracle.com/javaee/7/api/javax/persistence/Query.html" rel="nofollow" target="_blank">Query Javadocs</a></p>
<p><span> </span><a href="https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html" rel="nofollow" target="_blank">EntityManager Javadocs</a></p></div>How to fix error Unknown database in Hibernate/JPA2019-06-04T01:36:51-05:002019-06-04T01:36:51-05:00https://codejava.net/java-ee/jpa/how-to-fix-error-unknown-database-in-hibernate-jpaNam Ha Minhhainatu@gmail.com<div class="feed-description"><p>When developing Java applications that use <a href="frameworks/hibernate/java-hibernate-jpa-annotations-tutorial-for-beginners" target="_blank">Hibernate/JPA</a>, you may encounter this error:</p>
<pre class="brush:text">Unknown database ‘dbname’</pre>
<p>This error usually occurs when you import a project to your computer and the database name it uses is different than the database name on your computer. You change the database name but it doesn’t solve the problem.</p>
<p>The exception stack trace would look like this:</p>
<pre class="brush:text">javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
...
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
...
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'bookstore'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
...</pre>
<p>The real cause of the error is <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">Unknown database ‘bookstore’</span>. The database name is configured in the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">persistence.xml </span>file like this:</p>
<pre class="brush:xml"><?xml version="1.0" encoding="UTF-8"?>
<persistence...>
<persistence-unit name="BookStore">
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/bookstoredb" />
...
</properties>
</persistence-unit>
</persistence></pre>
<p>You check the database name in the JDBC URL and it is absolutely correct – But the error still occurs. It still mentions the old database name. You don’t understand why - spending hours to find what went wrong but you’re totally lost!</p>
<p>I was in such situation and nearly got upset about that problem. Fortunately, I figured out that there’s another location in which the database name is used. It is in the model classes, for example:</p>
<pre class="brush:java">@Entity
@Table(name = "category", catalog = "bookstore"...)
public class Category implements java.io.Serializable {
...
}</pre>
<p>Here, you can see the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">catalog </span>attribute of the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">@Table</span> annotation refers to the database name. Voila!</p>
<p>This code maybe generated by <a href="frameworks/hibernate/java-hibernate-reverse-engineering-tutorial-with-eclipse-and-mysql">Hibernate Reverse Engineering tool</a>, so you don’t notice. So to solve the error, you have to either:</p>
<ul>
<li>Update the database name in the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">catalog</span> attribute in the model classes, or</li>
<li>Delete all the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">catalog</span> attribute in the model classes.</li>
</ul>
<p>Then the error <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">Unknown database</span> error will be solved.</p></div><div class="feed-description"><p>When developing Java applications that use <a href="frameworks/hibernate/java-hibernate-jpa-annotations-tutorial-for-beginners" target="_blank">Hibernate/JPA</a>, you may encounter this error:</p>
<pre class="brush:text">Unknown database ‘dbname’</pre>
<p>This error usually occurs when you import a project to your computer and the database name it uses is different than the database name on your computer. You change the database name but it doesn’t solve the problem.</p>
<p>The exception stack trace would look like this:</p>
<pre class="brush:text">javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
...
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
...
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'bookstore'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
...</pre>
<p>The real cause of the error is <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">Unknown database ‘bookstore’</span>. The database name is configured in the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">persistence.xml </span>file like this:</p>
<pre class="brush:xml"><?xml version="1.0" encoding="UTF-8"?>
<persistence...>
<persistence-unit name="BookStore">
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/bookstoredb" />
...
</properties>
</persistence-unit>
</persistence></pre>
<p>You check the database name in the JDBC URL and it is absolutely correct – But the error still occurs. It still mentions the old database name. You don’t understand why - spending hours to find what went wrong but you’re totally lost!</p>
<p>I was in such situation and nearly got upset about that problem. Fortunately, I figured out that there’s another location in which the database name is used. It is in the model classes, for example:</p>
<pre class="brush:java">@Entity
@Table(name = "category", catalog = "bookstore"...)
public class Category implements java.io.Serializable {
...
}</pre>
<p>Here, you can see the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">catalog </span>attribute of the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">@Table</span> annotation refers to the database name. Voila!</p>
<p>This code maybe generated by <a href="frameworks/hibernate/java-hibernate-reverse-engineering-tutorial-with-eclipse-and-mysql">Hibernate Reverse Engineering tool</a>, so you don’t notice. So to solve the error, you have to either:</p>
<ul>
<li>Update the database name in the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">catalog</span> attribute in the model classes, or</li>
<li>Delete all the <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">catalog</span> attribute in the model classes.</li>
</ul>
<p>Then the error <span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">Unknown database</span> error will be solved.</p></div>How to fix JPA Problem: This project has JPA facet, but no JPA project could be created2019-05-11T01:45:04-05:002019-05-11T01:45:04-05:00https://codejava.net/java-ee/jpa/how-to-fix-jpa-problem-this-project-has-jpa-facet-but-no-jpa-project-could-be-createdNam Ha Minhhainatu@gmail.com<div class="feed-description"><p>When developing Java projects that use Hibernate/JPA, you may encounter this error in Eclipse IDE:</p>
<pre class="brush:text">This project has the JPA facet, but no JPA project could be created. See the error log for more details.</pre>
<p>This error looks like this in the Markers view in Eclipse:</p>
<p><img loading="lazy" style="display: block; margin-left: auto; margin-right: auto;" src="images/articles/javaee/jpa/jpa-problem/JPA_Problem_could_not_create_project.png" alt="JPA Problem could not create project" /></p>
<p>To solve this problem, right click on your project, click <strong>Properties</strong> in the context menu. In the <i>Project Properties</i> dialog, click <strong>Project Facets</strong> on the left tree. Then in the list on the right, uncheck the option JPA:</p>
<p><img loading="lazy" style="display: block; margin-left: auto; margin-right: auto;" src="images/articles/javaee/jpa/jpa-problem/Project_Facet_JPA.png" alt="Project Facet JPA" /></p>
<p>Click Apply and Close. You see the error is still there. Now right-click on the project and click <strong>Validate</strong> command in the context menu:</p>
<p><img loading="lazy" style="display: block; margin-left: auto; margin-right: auto;" src="images/articles/javaee/jpa/jpa-problem/Validate_command.png" alt="Validate command" /></p>
<p>The error JPA problem will be gone. Happy coding!</p></div><div class="feed-description"><p>When developing Java projects that use Hibernate/JPA, you may encounter this error in Eclipse IDE:</p>
<pre class="brush:text">This project has the JPA facet, but no JPA project could be created. See the error log for more details.</pre>
<p>This error looks like this in the Markers view in Eclipse:</p>
<p><img loading="lazy" style="display: block; margin-left: auto; margin-right: auto;" src="images/articles/javaee/jpa/jpa-problem/JPA_Problem_could_not_create_project.png" alt="JPA Problem could not create project" /></p>
<p>To solve this problem, right click on your project, click <strong>Properties</strong> in the context menu. In the <i>Project Properties</i> dialog, click <strong>Project Facets</strong> on the left tree. Then in the list on the right, uncheck the option JPA:</p>
<p><img loading="lazy" style="display: block; margin-left: auto; margin-right: auto;" src="images/articles/javaee/jpa/jpa-problem/Project_Facet_JPA.png" alt="Project Facet JPA" /></p>
<p>Click Apply and Close. You see the error is still there. Now right-click on the project and click <strong>Validate</strong> command in the context menu:</p>
<p><img loading="lazy" style="display: block; margin-left: auto; margin-right: auto;" src="images/articles/javaee/jpa/jpa-problem/Validate_command.png" alt="Validate command" /></p>
<p>The error JPA problem will be gone. Happy coding!</p></div>[Fixed] No Persistence provider for EntityManager named XXX2021-11-06T08:01:16-05:002021-11-06T08:01:16-05:00https://codejava.net/java-ee/jpa/no-persistence-provider-for-entitymanager-named-xxxNam Ha Minhhainatu@gmail.com<div class="feed-description"><p>In this post, I’d like to share some solutions that fix the following error in Java development with Hibernate/JPA:</p>
<pre class="brush:xml">Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named XXX
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)</pre>
<p>where XXX is the persistence unit name declared in the persistence.xml file of your project, something like this:</p>
<pre class="brush:xml"><?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
<persistence-unit name="BookstoreWebsite">
<properties>
...
</properties>
</persistence-unit>
</persistence></pre>
<p>Here are 4 different causes of this error, and how to fix in each case:</p>
<p> </p>
<h2>1. Persistent unit name in code does not match the one in JPA config file</h2>
<p>In Java code, the persistence unit name is specified like this:</p>
<pre class="brush:java">entityManagerFactory = Persistence.createEntityManagerFactory("BookStoreWebsite");</pre>
<p>But in the persistence.xml file, it is declared like this:</p>
<pre class="brush:xml">the persistence.xml file, it is declared like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
<persistence-unit name="BookstoreWebsite">
<properties>
...
</properties>
</persistence-unit>
</persistence></pre>
<p>Do you see the difference? It is the letter s/S in Bookstore. So check persistence name in both code and XML file carefully - ensure that they are the same.</p>
<h2><br />2. Typos in name of JPA config file</h2>
<p>The name of JPA config file must be <span style="background-color: #ffff00;"><strong><span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">persistence.xml</span></strong></span>, but somehow you name it slightly different, e.g. peristence.xml - a letter s is missing. So check typos in file name to make sure it is persistence.xml exactly.</p>
<h2><br />3. JPA Config file is not in the right location</h2>
<p>By default, the persistence.xml file must be present in the classpath, under <span style="color: #800000; background-color: #ffff00;"><strong><span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New';">src/META-INF</span></strong></span> folder of the project, as shown below:</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="images/articles/javaee/jpa/persistence_xml_meta-inf.png" alt="persistence xml meta-inf" /></p>
<p>So make sure that you put the JPA config file in the right location.</p>
<h2><br />4. Incompatible Hibernate core version</h2>
<p>Another cause of the error <i>No Persistence provider for EntityManager named XXX</i> is the version of Hibernate core dependency in your project. For example, hibernate-core-5.0.12 is known to cause this kind of error, whereas hibernate-core-5.2.12 works fine.</p>
<p>So try to use different the version of Hibernate core if you encounter this problem.</p>
<p> </p>
<h2>5. Wrong Dependency Declaration of Hibernate core</h2>
<p>Another reason that causes the error No Persistence provider for Entity Manager is the delcared type and scope of Hibernate core dependency is like this:</p>
<pre class="brush:xml"><dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Final</version>
<type>pom</type>
<scope>compile</scope>
</dependency></pre>
<p>Remove this kind of type (pom) and scope (compile), and the error will be resolved.</p>
<p> </p>
<p>Okay, so far I’ve shared with you guys, 4 solutions which you could consider to fix the error <i>No Persistence provider for EntityManager named XXX. </i>Hope you find this post helpful.</p>
<p> </p>
<h2>How to Solve other Hibernate/JPA errors:</h2>
<ul>
<li><a href="java-ee/jpa/how-to-fix-error-unknown-database-in-hibernate-jpa" target="_blank">How to fix error Unknown database in Hibernate/JPA</a></li>
<li><a href="java-ee/jpa/how-to-fix-jpa-problem-this-project-has-jpa-facet-but-no-jpa-project-could-be-created" target="_blank">How to fix JPA Problem: This project has JPA facet, but no JPA project could be created<br /><br /></a></li>
</ul></div><div class="feed-description"><p>In this post, I’d like to share some solutions that fix the following error in Java development with Hibernate/JPA:</p>
<pre class="brush:xml">Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named XXX
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:61)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)</pre>
<p>where XXX is the persistence unit name declared in the persistence.xml file of your project, something like this:</p>
<pre class="brush:xml"><?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
<persistence-unit name="BookstoreWebsite">
<properties>
...
</properties>
</persistence-unit>
</persistence></pre>
<p>Here are 4 different causes of this error, and how to fix in each case:</p>
<p> </p>
<h2>1. Persistent unit name in code does not match the one in JPA config file</h2>
<p>In Java code, the persistence unit name is specified like this:</p>
<pre class="brush:java">entityManagerFactory = Persistence.createEntityManagerFactory("BookStoreWebsite");</pre>
<p>But in the persistence.xml file, it is declared like this:</p>
<pre class="brush:xml">the persistence.xml file, it is declared like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence ...>
<persistence-unit name="BookstoreWebsite">
<properties>
...
</properties>
</persistence-unit>
</persistence></pre>
<p>Do you see the difference? It is the letter s/S in Bookstore. So check persistence name in both code and XML file carefully - ensure that they are the same.</p>
<h2><br />2. Typos in name of JPA config file</h2>
<p>The name of JPA config file must be <span style="background-color: #ffff00;"><strong><span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New'; color: #800000;">persistence.xml</span></strong></span>, but somehow you name it slightly different, e.g. peristence.xml - a letter s is missing. So check typos in file name to make sure it is persistence.xml exactly.</p>
<h2><br />3. JPA Config file is not in the right location</h2>
<p>By default, the persistence.xml file must be present in the classpath, under <span style="color: #800000; background-color: #ffff00;"><strong><span style="font-size: 10pt; line-height: 107%; font-family: 'Courier New';">src/META-INF</span></strong></span> folder of the project, as shown below:</p>
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="images/articles/javaee/jpa/persistence_xml_meta-inf.png" alt="persistence xml meta-inf" /></p>
<p>So make sure that you put the JPA config file in the right location.</p>
<h2><br />4. Incompatible Hibernate core version</h2>
<p>Another cause of the error <i>No Persistence provider for EntityManager named XXX</i> is the version of Hibernate core dependency in your project. For example, hibernate-core-5.0.12 is known to cause this kind of error, whereas hibernate-core-5.2.12 works fine.</p>
<p>So try to use different the version of Hibernate core if you encounter this problem.</p>
<p> </p>
<h2>5. Wrong Dependency Declaration of Hibernate core</h2>
<p>Another reason that causes the error No Persistence provider for Entity Manager is the delcared type and scope of Hibernate core dependency is like this:</p>
<pre class="brush:xml"><dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.0.0.Final</version>
<type>pom</type>
<scope>compile</scope>
</dependency></pre>
<p>Remove this kind of type (pom) and scope (compile), and the error will be resolved.</p>
<p> </p>
<p>Okay, so far I’ve shared with you guys, 4 solutions which you could consider to fix the error <i>No Persistence provider for EntityManager named XXX. </i>Hope you find this post helpful.</p>
<p> </p>
<h2>How to Solve other Hibernate/JPA errors:</h2>
<ul>
<li><a href="java-ee/jpa/how-to-fix-error-unknown-database-in-hibernate-jpa" target="_blank">How to fix error Unknown database in Hibernate/JPA</a></li>
<li><a href="java-ee/jpa/how-to-fix-jpa-problem-this-project-has-jpa-facet-but-no-jpa-project-could-be-created" target="_blank">How to fix JPA Problem: This project has JPA facet, but no JPA project could be created<br /><br /></a></li>
</ul></div>