使用EntityManager的Spring数据:NullPointerException

时间:2016-01-13 15:00:19

标签: java spring hibernate spring-data spring-data-jpa

我是春季数据的新手。我正在尝试使用spring数据和entitymanager构建一个小的java应用程序。该项目的结构如下:

enter image description here

对于spring配置我创建了一个类,我在这个类中定义了bean,用于以这种方式创建实体管理器bean

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();
    }

}

为了能够访问数据库,我创建了DAO类UserDao,它只允许在表User中创建一行。

界面IUserDao

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

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;
        }
    }

}

这就是用户的实体类:

用户实体

@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;
    }
}

这是对已完成内容的一个小测试

测试

public class UserTest {

    @Autowired
    UserDao userDao;

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

}

但问题是,如果我运行main,我会得到异常NullPointerException,因为userDao的值为null,因此未定义UserDao bean。 我做了什么问题?

3 个答案:

答案 0 :(得分:1)

在你的主要方法中,你试图自动装配一些静态的东西。这不会起作用。请参阅较长的解释here

有关如何使用Spring执行单元测试的综合文档,请阅读documentation此处。

答案 1 :(得分:1)

您正尝试在更简单的标准环境中测试Spring企业环境。企业环境需要一些设置才能为您服务。一个好的开始是http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html

一旦你获得了正确的部分,那么构建和测试就会变得更加容易和有趣。

答案 2 :(得分:0)

然后你应该从junit类初始化Spring Context。你发布的代码没有显示这个,所以也许空指针是由于这个错误。

public class UserTest {

    @Autowired
    UserDao userDao;

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

}

您应该使用以下内容注释您的类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);
    }

}