PersistenceContext 和 Autowire 依赖项注入注释不起作用。我得到NullPointerException。我通过在各自的Abstract类中创建getEntityManager和getDaoInstance方法来解决该问题。但是,我仍然想弄清楚/理解为什么批注最初不起作用。
我查看了StackOverflow上的相关内容,但是运气不好。
PS::我是Java的新
AbstractDao 类,带有getEntityManager方法(完整代码,https://pastebin.com/6nKh1ujY)
package com.beetlehand.model.dao;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;
public abstract class AbstractDao<T, S> implements AbstractDaoInterface<T, S> {
protected EntityManager entityManager;
public EntityManager getEntityManager() {
if(this.entityManager == null) {
this.entityManager = Persistence
.createEntityManagerFactory("NewPersistenceUnit")
.createEntityManager();
}
return this.entityManager;
}
// more code below
}
在Dao类中如何调用 getEntityManager 方法的示例(完整代码,https://pastebin.com/dhjz17sN)
package com.beetlehand.model.dao;
import com.beetlehand.model.AttributeEntity;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class AttributeDao extends AbstractDao<AttributeEntity, Integer> {
public AttributeEntity getById(Integer id) {
if(id == null) return null;
return getEntityManager().find(AttributeEntity.class, id);
}
// more code below
}
AbstractService 和getDaoInstance方法(完整代码,https://pastebin.com/H4HGB43y)
package com.beetlehand.model.service;
import com.beetlehand.model.dao.AbstractDaoInterface;
import org.apache.commons.lang3.text.WordUtils;
import java.lang.reflect.Constructor;
import java.util.HashMap;
public class AbstractService {
protected HashMap<String, Object> daoInstance = new HashMap<>();
public AbstractDaoInterface getDaoInstance(String className) {
try {
if(!daoInstance.containsKey(className)) {
className = WordUtils.capitalizeFully(className, new char[]{'_'})
.replaceAll("_", "");
Class<?> clazz = Class.forName("com.beetlehand.model.dao." + className);
Constructor<?> ctr = clazz.getConstructor();
daoInstance.put(className, ctr.newInstance());
}
}catch(Exception ex) {
ex.printStackTrace();
return null;
}
return (AbstractDaoInterface) daoInstance.get(className);
}
}
在服务类中调用 getDaoInstance 方法的示例(完整代码,https://pastebin.com/86yNSmsX)
package com.beetlehand.model.service;
import com.beetlehand.model.*;
import com.beetlehand.model.dao.AbstractDaoInterface;
public class CatalogService extends AbstractService {
public AttributeEntity addAttribute(AttributeEntity attributeEntity) {
AbstractDaoInterface attributeDao = this.getDaoInstance("attribute_dao");
attributeDao.saveRow(attributeEntity);
return attributeEntity;
}
public AttributeValueEntity addAttributeValue(AttributeValueEntity attributeValueEntity) {
AbstractDaoInterface attributeValueDao = this.getDaoInstance("attribute_value_dao") ;
attributeValueDao.saveRow(attributeValueEntity);
return attributeValueEntity;
}
// more code below
}