简体   繁体   English

使用EntityManager的Spring数据:NullPointerException

[英]Spring data using EntityManager: NullPointerException

I'm new in spring data. 我是春季数据的新手。 I'm trying to build a small java application using spring data and entitymanager. 我正在尝试使用spring数据和entitymanager构建一个小的Java应用程序。 The structure of the project is the following: 该项目的结构如下:

在此处输入图片说明

For the spring configuration I created a class and I defined in this class beans that will be used to create an entity manager bean with this way 对于spring配置,我创建了一个类,并在该类中定义了bean,该bean将用于以这种方式创建实体管理器bean

SpringConfiguration: SpringConfiguration:

@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-mysql.properties" })
@ComponentScan({ "com.spring.data.persistence" })
public class SpringConfiguration implements TransactionManagementConfigurer{

    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();

        driverManagerDataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        driverManagerDataSource.setUrl(env.getProperty("jdbc.url"));
        driverManagerDataSource.setUsername(env.getProperty("jdbc.user"));
        driverManagerDataSource.setPassword(env.getProperty("jdbc.pass"));
        return driverManagerDataSource;
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        localContainerEntityManagerFactoryBean.setDataSource(dataSource());
        localContainerEntityManagerFactoryBean.setJpaDialect(jpaDialect());
        localContainerEntityManagerFactoryBean.setPackagesToScan(new String[] { "com.spring.data.persistence.model" });
        localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaAdapter());
        return localContainerEntityManagerFactoryBean;
    }

    @Bean
    public HibernateJpaVendorAdapter jpaAdapter() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        Boolean showSql = true;
        hibernateJpaVendorAdapter.setShowSql(showSql);
        hibernateJpaVendorAdapter.setDatabasePlatform(env.getProperty("hibernate.dialect"));
        hibernateJpaVendorAdapter.setGenerateDdl(false);
        return hibernateJpaVendorAdapter;
    }

    @Bean
    public JpaDialect jpaDialect() {
        return new HibernateJpaDialect();
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {
        PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor = new PersistenceExceptionTranslationPostProcessor();
        persistenceExceptionTranslationPostProcessor.setRepositoryAnnotationType(Repository.class);
        return persistenceExceptionTranslationPostProcessor;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        EntityManagerFactory entityManagerFactory = entityManagerFactory().getObject();
        return new JpaTransactionManager(entityManagerFactory);
    }

    @Bean
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return transactionManager();
    }

}

To be able to access to the database, I create the DAO class UserDao that allows only to create a row in the table User. 为了能够访问数据库,我创建了DAO类UserDao,该类仅允许在表User中创建一行。

The interface IUserDao 接口IUserDao

public interface IUserDao {
    public User create(User user);
}

The UserDao class UserDao类

@Repository
public class UserDao implements IUserDao{

    @PersistenceContext
    private EntityManager entityManager;

    public UserDao()
    {
        super();
    }
    public User create(User user) {
        try {
            this.entityManager.persist(user);
            return user;
        } catch (PersistenceException ex) {
            ex.printStackTrace();
            return null;

        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
            return null;
        }
    }

}

And that's the entity class of the User: 这就是用户的实体类:

The User Entity 用户实体

@Entity
public class User {
    @Id
    @GeneratedValue
    @Column(name="USER_ID")
    private int id;

    @Column(name="USER_NAME")
    String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

And this is a small test of what's done 这是对完成情况的一个小测试

The test 考试

public class UserTest {

    @Autowired
    UserDao userDao;

    @Test
    public void test() {
        User user=new User();
        user.setName("User1");
        userDao.create(user);
    }

}

But the problem is that if I run the main I get the exception NullPointerException because userDao has as value null so the UserDao bean isn't defined. 但是问题是,如果我运行主程序,则会得到NullPointerException异常,因为userDao的值为null,因此未定义UserDao Bean。 What's the problem in what I did? 我的工作有什么问题?

In your main method you are trying to autowire something static. 在您的主要方法中,您尝试自动连接静态的东西。 That is not going to work. 那是行不通的。 See the longer explanation here . 请参阅此处的详细说明。

For a comprehensive doc on how to perform unit testing with Spring, please read the documentation here. 有关如何使用Spring进行单元测试的全面文档,请阅读此处的文档

You are trying to test a spring enterprise environment in a much simpler standard environment. 您正在尝试在更简单的标准环境中测试Spring企业环境。 The enterprise environment requires some setup before it will work for you. 企业环境需要先进行一些设置,然后才能为您工作。 A good place to start is http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html . 一个很好的起点是http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html

Once you get the right pieces in place it then becomes a whole lot easier and interesting to build and test. 一旦正确放置了部件,构建和测试就变得非常容易和有趣。

Then you should initialize Spring Context from your junit class. 然后,您应该从junit类初始化Spring Context。 The code you posted does not show this so maybe the null pointer is due to this error. 您发布的代码没有显示此内容,因此空指针可能是由于此错误引起的。

public class UserTest {

    @Autowired
    UserDao userDao;

    @Test
    public void test() {
        User user=new User();
        user.setName("User1");
        userDao.create(user);
    }

}

You should annotate your class UserTest with something like: 您应该使用类似以下内容注释类UserTest:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class, loader = AnnotationConfigContextLoader.class)
public class UserTest {
    @Autowired
    UserDao userDao;

    @Test
    public void test() {
        User user=new User();
        user.setName("User1");
        userDao.create(user);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring中的EntityManager上的NullPointerException - NullPointerException on entityManager in Spring 使用@PersistenceContext的EntityManager的NullPointerException - NullPointerException for EntityManager using @PersistenceContext 使用 EntityManager 查询 Spring JPA NullPointerException - Spring JPA NullPointerException in query with EntityManager 无法使用Spring Managed EntityManager保留数据 - Not able to persist data using spring managed EntityManager 在Spring数据存储库顶部使用EntityManager - Using EntityManager on top of Spring Data Repositories Spring 使用 EntityManager 启动多个数据源 - Spring boot multiple data sources using EntityManager Spring Data JPA/Hibernate - 使用 EntityManager 进行查询 - Spring Data JPA/Hibernate - using EntityManager for queries java.lang.NullPointerException:在提取数据时无法在 Spring MVC 中调用“javax.persistence.EntityManager 错误” - java.lang.NullPointerException: Cannot invoke "javax.persistence.EntityManager error in Spring MVC while pulling data 使用EntityManager的persist()函数时的java.lang.NullPointerException(Spring 4 ORM) - java.lang.NullPointerException when using EntityManager's persist() func (Spring 4 ORM) 在Java中使用EntityManager和Criteria时发生NullPointerException - NullPointerException when using EntityManager and Criteria in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM