java 为什么实体管理器在Spring Boot 时没有自动连接?

bxjv4tth  于 2023-01-15  发布在  Java
关注(0)|答案(1)|浏览(222)

我有一个抽象仓库类,我在里面使用了entitymanager,我想用spring boot初始化它,但是它给出了一个错误,这个对象是null,我该怎么办?我在entitymanager字段上使用了@PersistenceContext,在主类上使用了@EnableJpaRepositories,但是结果是一样的,我该怎么办?

@Getter
@NoArgsConstructor
@Transactional
@Repository
@Qualifier("personDAO")
public abstract class AbstractDAO<T> {
    public EntityManager em;
    @Transient
    protected Class clazz;

    public AbstractDAO(EntityManager em) {
        this.em = em;
    }
    public void persist(T model) {
        em.persist(model);
    }

    public void delete(T model) {
        em.remove(model);
    }

    public boolean deleteById(int id) {
        boolean result= em.createQuery("delete from "+clazz.getSimpleName()+ " o where o.id=" + id).executeUpdate() > 0;
        return result;
    }

    public List<T> findAll() {
        return em.createQuery("select o from "+clazz.getSimpleName()+" o").getResultList();}

    public T findById(int id) {
        return (T) em.find(clazz, id);
    }
}

例外情况:

Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:116)
    at java.base/java.lang.reflect.Method.invoke(Method.java:578)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.NullPointerException: Cannot invoke "jakarta.persistence.EntityManager.persist(Object)" because "this.em" is null
    at org.isoft.repo.AbstractDAO.persist(AbstractDAO.java:29)
    at org.isoft.App.main(App.java:35)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    ... 2 more
zsbz8rwp

zsbz8rwp1#

如果您想在抽象类中为实现类注入一些bean,则需要在初始化方法上使用Autowired注解,而不是像这样的构造函数

@Getter
@NoArgsConstructor
@Transactional
@Repository
@Qualifier("personDAO")
public abstract class AbstractDAO<T> {
    public EntityManager em;
    @Transient
    protected Class clazz;

    @Autowired
    public init(EntityManager em) {
        this.em = em;
    }
    public void persist(T model) {
        em.persist(model);
    }

    public void delete(T model) {
        em.remove(model);
    }

    public boolean deleteById(int id) {
        boolean result= em.createQuery("delete from "+clazz.getSimpleName()+ " o where o.id=" + id).executeUpdate() > 0;
        return result;
    }

    public List<T> findAll() {
        return em.createQuery("select o from "+clazz.getSimpleName()+" o").getResultList();}

    public T findById(int id) {
        return (T) em.find(clazz, id);
    }
}

否则,Spring将不会注入bean,并且对于此抽象的实现,它将为null
您还可以在该类的每个实现中注入此Bean

相关问题