如何使用Spring MVC使用Entity Manager将数据插入表中

时间:2019-03-10 01:02:57

标签: java spring spring-boot

我试图将数据插入到我的客户表中,但是我一直收到空指针异常。

这是我设置EntityManager变量的方式。

@Repository
public class CustomerInsertRepository {

private EntityManagerFactory entityManagerFactory;


@PersistenceContext
private EntityManager entityManager = 
entityManagerFactory.createEntityManager();

然后我进入insertWithQuery函数,这是我尝试在客户表中插入数据的地方

@Transactional
public void insertWithQuery(Customer customer)
{
    entityManager.createNativeQuery("INSERT INTO customer "
            + " (first_name last_name, street_address, zip_code, email, city, state) "
            + " VALUES (?, ?, ?, ?, ?, ?, ?)")
    .setParameter(1, customer.getFirstName())
    .setParameter(2, customer.getLastName())
    .setParameter(3, customer.getAddress())
    .setParameter(4, customer.getZipcode())
    .setParameter(5, customer.getEmail())
    .setParameter(6, customer.getCity())
    .setParameter(7, customer.getState())
    .executeUpdate();
}

最后,我通过运行一个测试用例来执行这个insertWithQuery函数。

 @Test
 public void nativeQueryTest()
 {
    Customer customer = new Customer();
    customer.setFirstName("Bob");
    customer.setLastName("Jones");
    customer.setAddress("123 baker st");
    customer.setZipcode("123545");
    customer.setEmail("example@example.com");
    customer.setCity("New York");
    customer.setState("NY");


    insertWithQuery(customer);
 }

通过运行测试用例,我的NullPointerException错误就在这里

@PersistenceContext
private EntityManager entityManager = 
entityManagerFactory.createEntityManager();

这是我的全班课

@Repository
public class CustomerInsertRepository {

private EntityManagerFactory entityManagerFactory;


@PersistenceContext
private EntityManager entityManager = entityManagerFactory.createEntityManager();

@Transactional
public void insertWithQuery(Customer customer)
{
    entityManager.createNativeQuery("INSERT INTO customer "
            + " (first_name last_name, street_address, zip_code, email, city, state) "
            + " VALUES (?, ?, ?, ?, ?, ?, ?)")
    .setParameter(1, customer.getFirstName())
    .setParameter(2, customer.getLastName())
    .setParameter(3, customer.getAddress())
    .setParameter(4, customer.getZipcode())
    .setParameter(5, customer.getEmail())
    .setParameter(6, customer.getCity())
    .setParameter(7, customer.getState())
    .executeUpdate();
}

@Test
public void nativeQueryTest()
{
    Customer customer = new Customer();
    customer.setFirstName("Bob");
    customer.setLastName("Jones");
    customer.setAddress("123 baker st");
    customer.setZipcode("123545");
    customer.setEmail("example@example.com");
    customer.setCity("New York");
    customer.setState("NY");


    insertWithQuery(customer);
}


}

我不太了解如何解决此错误。谢谢

2 个答案:

答案 0 :(得分:0)

方法createEntityManager()可能是静态的

尝试:

PasswordResetView

Instaead

from django.contrib.auth.forms import PasswordResetForm as DjangoPasswordResetForm
from rest_auth.serializers import (
    PasswordResetSerializer as RestAuthPasswordResetSerializer
)
from rest_auth.views import PasswordResetView as RestAuthPasswordResetView


class PasswordResetForm(DjangoPasswordResetForm):
    def get_users(self, email):
        users = tuple(super().get_users(email))
        if users:
            return users
        msg = _('"{email}" was not found in our system.')
        raise ValidationError({'email': msg.format(email=email)})


class PasswordResetSerializer(RestAuthPasswordResetSerializer):
    password_reset_form_class = PasswordResetForm


class PasswordResetView(RestAuthPasswordResetView):
    serializer_class = PasswordResetSerializer

    def __init__(self, *args, **kwargs):
        """Prints the name of the class if it is used."""
        print(self.__class__.__name__)
        super().__init__(*args, **kwargs)

答案 1 :(得分:0)

首先,空指针出现是因为您有一个从未初始化的字段entityManagerFactory,因此它具有空值,但是您调用了entityManagerFactory.createEntityManager()(因此这是null.createEntityManager()调用)初始化entityManager字段时。

您可以尝试在@Autowired上放置entityManagerFactory注释-但是,我不明白为什么您不自动装配Spring提供的entityManager而是创建自己的注释。

另外,您似乎在@PersistenceContext上有entityManager注释-如果您在EJB容器中运行或使用CDI进行依赖项注入,则应该注入现有的entityManager -但不是,您使用的是@Repository注释,该注释来自Spring。然后您自己初始化该字段。绝对应该删除此注释(我想您已将其放在其中以注入entityManager,但是如果这样做不起作用,则添加了初始化代码-entityManagerFactory.createEntityManager())。或更好-用@Autowire代替,而应该删除初始化代码。

例如只是有

@Repository
public class CustomerInsertRepository {

@Autowired
private EntityManager entityManager;
...