为什么在Spring Boot Project中直接使用EntityManger时得到NullPointerException?

问题描述

我在两个实体ProductCategoryDifferentProducts之间创建了一个一对多关系,并尝试通过直接使用ProductCategory来持久化EntityManager。 但是,当我使用下面的代码持久化对象时,我得到了null-pointer Exception。我使用了@PersistenceContext注释使EntityManager实例由spring上下文管理。

public String AddProducts(){

        ProductCategory productCategory = new ProductCategory();
        ProductServiceImpl productService =new ProductServiceImpl();
        productCategory.setName("Type1");
        productService.saveProductCategory(productCategory);
        return "ProductAdded.. :)";
    }

我的实体类:-

@Entity
public class ProductCategory {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;

    @OnetoMany(cascade = {PERSIST,MERGE},fetch = FetchType.LAZY)
    private List<DifferentProducts> differentProducts;
    //getter and setters
}

第二:-

@Entity
public class DifferentProducts {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String productname;
    private String cost;
    //getter and setter
}

ProductServiceImpl类:=

public class ProductServiceImpl implements ProductService{

    @Autowired
    private ProductsRepository productsRepository;

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<ProductCategory> getAllProducts() {
        return null;
    }

    @Override
    public void saveProductCategory(ProductCategory productCategory) {
        entityManager.persist(productCategory);
    }
}

注意:-

我已经按照JPA的要求预先在数据库中创建了表格。因此,我没有包括在内 spring.jpa.hibernate.ddl-auto= update 在我的application.properties文件中。

谢谢你的话对我来说永远是有价值的。.

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)