pmaurais
pmaurais

Reputation: 924

"package javax.persistence does not exist" using spring-data-jpa and IntelliJ

I'm starting a project using spring-data-jpa in IntelliJ but I am failing to load javax.persistence ("package javax.persistence does not exist").

I have been at it for four hours with what seems be be a very simple problem. I used the standard IntelliJ UI to create the project and selected the spring framework and spring-data-jpa options.

My only code is:

import javax.persistence.entity;

@entity
public class customer {

}

The project fails to build and the tool tips in the IDE say "Can not resolve symbol persistence" What am I missing?

My directory structure can be found below: enter image description here

Upvotes: 21

Views: 88908

Answers (5)

Curtis Yallop
Curtis Yallop

Reputation: 7329

In java 11 (released 2018), the java EE libraries were moved from the built-in core to optional dependencies (See http://openjdk.java.net/jeps/320). So you may need to add:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>javax.persistence-api</artifactId>
    <version>2.2</version>
</dependency>

(hibernate-entitymanager has this as a dependency so that's probably why adding it fixed the problem - see https://repo1.maven.org/maven2/org/hibernate/hibernate-entitymanager/5.6.15.Final/hibernate-entitymanager-5.6.15.Final.pom)

Also related: In 2017, Java EE was transferred to Eclipse and renamed to Jakarta EE (Oracle owned the name "Java").

The latest imports are now under "jakarta": eg import jakarta.persistence.EntityManager;.

Hibernate 5 still uses JPA 2.2 (javax) rather but Hibernate 6 uses JPA 3.0 (jakarta). Ensure you do not have both hibernate 5 and 6 in your mvn dependency:tree.

Upvotes: 13

Shehan Jayalath
Shehan Jayalath

Reputation: 704

In my case, the answer was straightforward:

project details:
Spring Boot, Maven, Java 17, Multi-Module

I just needed to import:

 import jakarta.persistence.*;

NOTE

This import was not valid in my case

X => import javax.persistence.*;

Upvotes: 3

Ashrik Ahamed
Ashrik Ahamed

Reputation: 455

You might have added hibernates in library, instead of modules in project structure.

Upvotes: -1

pmaurais
pmaurais

Reputation: 924

All I needed to do was add the hibernate libs from maven through the project structure dialog (hibernate-entitymanager)

Upvotes: 13

user2743227
user2743227

Reputation:

Three things:

Firstly you type "Entity" wrong. Java classes are case sensitive so it should be @Entity.

Secondly, javax.persistence is not always packaged with the core JDK so you need to download it. You can get it here: https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api/2.2

Finally, your directory structure can result in some issues. I recommend changing it to

src (directory)

-> main (directory)

-> -> java (directory)

-> -> -> Driver (file)

-> -> -> Data.xml (file)

-> -> -> customer (file)

Upvotes: 4

Related Questions