簡體   English   中英

SpringBoot Application和Hibernate(entityManager為null)

[英]SpringBoot Application and Hibernate (entityManager is null)

我有示例 SprintBoot 應用程序

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);
    }

}

我的application.properties,這里配置datasource和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

我有簡單的 controller 方法

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

和服務


@Service
public class MyService {

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

結果是

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

我想要簡單的 springboot 和 hibernate 應用程序,帶有初始化的 entityManager 用於查詢數據庫。

我究竟做錯了什么?

我通過簡單地將所有 import javax.persistence 替換為 jakarta.persistence 解決了我的問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM