简体   繁体   中英

SpringBoot Application and Hibernate (entityManager is null)

I have example SprintBoot application

package com.example.demo2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
@EnableJpaRepositories(basePackages="com.example.demo2")
public class Demo2Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo2Application.class, args);
    }

}

My application.properties, here configuration datasource and jpa hibernate

spring.datasource.url= jdbc:postgresql://localhost:5432/testdb
spring.datasource.username= admin
spring.datasource.password= admin

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.ddl-auto= update

and i have simple controller method

    @GetMapping("/get")
    public List<Movie> getMethod(){
        return myService.myMethod();
    }

and service


@Service
public class MyService {

    @PersistenceContext
    private EntityManager entityManager;
    @Transactional
    public List<Movie> myMethod() {
        List<Movie> myList = entityManager.createQuery("from Movie").getResultList();
        return myList;
    }
}

Result is

java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManager.createQuery(String)" because "this.entityManager" is null

I want simple springboot and hibernate application with initialized entityManager for query to db.

What am I doing wrong?

I solved my problem by simply replacing all import javax.persistence with jakarta.persistence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM