在SessionFactory中获取NullPointerException

时间:2017-07-19 05:29:55

标签: java spring hibernate model-view-controller

使用java @Bean注释

配置Hibernate
@Configuration
@ComponentScan(basePackages = {"com.worldofshopping.BackendShop"})
@ComponentScan(basePackages = {"com.worldofshopping"})
@EnableTransactionManagement
public class HibernateConfig {
    BasicDataSource dataSource;
    // Change the below final variable value based on database you choose

    private final static String DATABASE_URL = "jdbc:h2:~/rahul";
    private final static String DATABASE_DRIVER = "org.h2.Driver";
    private final static String DATABASE_DIALECTS = "org.hibernate.dialect.H2Dialect";
    private final static String DATABASE_USERNAME = "sa";
    private final static String DATABASE_PASSWORD = "sa";

    // Database will be available
    @Bean("dataSource")
    public DataSource getSource() {
        dataSource = new BasicDataSource();
        // Providing database connection Information
        dataSource.setDriverClassName(DATABASE_DRIVER);
        dataSource.setUrl(DATABASE_URL);
        dataSource.setUsername(DATABASE_USERNAME);
        dataSource.setPassword(DATABASE_PASSWORD);

        return dataSource;
    }

    // Database will be available
    @Autowired
    @Bean
    public SessionFactory getSessionFactory(DataSource datasource) {
        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
        builder.addProperties(getHibernateProperties());
        builder.scanPackages("com.worldofshopping.BackendShopndShop.dto");
        return builder.buildSessionFactory();
    }

    // For Hibernate property return
    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", DATABASE_DIALECTS);
        properties.put("hibernate.show_sql", "true");
        properties.put("hibernate.format_sql", "true");
        properties.put("hibernate.hbm2ddl.auto", "update");

        return properties;
    }

    // HibernateTransactionManager
    @Autowired
    @Bean
    public HibernateTransactionManager getTransactionManagement(SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
        return transactionManager;
    }
}


@Repository("userDao")
@Transactional
public class Userdaoimpl implements Userdao {

    @Autowired(required = true)
    private SessionFactory sessionFactory;

    @Override
    public User getUserByUsername(String email) {
        String command = "from User where email=:parameter";
        Query<User> query = sessionFactory.getCurrentSession().createQuery(command, User.class);
        query.setParameter("parameter", email);
        try {
            return query.getSingleResult();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean add(User user) {
        try {
            Cart cart = new Cart();
            cart.setUser(user);
            user.setCart(cart);
            sessionFactory.getCurrentSession().save(user);
            return true;
        } catch (Exception msg) {
            msg.printStackTrace();
            System.out.println(msg);
            return false;
        }
    }

    @Override
    public boolean update(User user) {
        try {
            sessionFactory.getCurrentSession().update(user);
            return true;
        } catch (Exception msg) {
            msg.printStackTrace();
            System.out.println("Something error occured during Update " + msg);
            return false;
        }
    }

    @Override
    public boolean delete(String email) {
        User user = getUserByUsername(email);
        user.setEnabled(false);
        try {
            sessionFactory.getCurrentSession().update(user);
            return true;
        } catch (Exception msg) {
            msg.printStackTrace();
            System.out.println("Something error occured during delete");
            return false;
        }
    }

    @Override
    public User getUserById(Long user_id) {

        try {
            return sessionFactory.getCurrentSession().get(User.class, Long.valueOf(user_id));

        } catch (Exception msg) {
            msg.printStackTrace();
            System.out.println("Something error occured during Update");
            return null;
        }
    }

}

主要方法:

public class App {

    public static void main(String[] args) {
        User user = new User();
        user.setAddress("New Delhi");
        user.setContact("9988776655");
        user.setEmail("komal@gmail.com");
        user.setEnabled(true);
        user.setName("Komal");
        user.setPassword("komal");
        user.setRole("CUSTOMER");
        Userdao userdao = new Userdaoimpl();
        userdao.add(user);
    }
}

异常堆栈跟踪:

  

显示java.lang.NullPointerException        显示java.lang.NullPointerException       在com.worldofshopping.BackendShop.daoimpl.Userdaoimpl.add(Userdaoimpl.java:37)       在com.worldofshopping.BackendShop.App.main(App.java:25)

任何人都可以帮助我使用@Repository("userDao") @Transactional

开始交易

我也尝试在junit上运行但仍然得到同样的错误!!

2 个答案:

答案 0 :(得分:1)

您只在主要方法中构建了UserUserdaoimpl!问自己如何启动SessionFactory和其他@Bean

尝试通过 spring context spring boot 应用程序运行应用程序。然后获取userdao Bean来调用add方法。

答案 1 :(得分:0)

如果您想在JUnit测试中试用您的应用程序,您应该注册这样的上下文:

{key: value for key, value in d.iteritems()  if not key.startswith('OS::')}

{u'flavor': u'm1.small',
 u'floating_ip': u'xyz',
 u'image': u'RHEL-7.2',
 u'key': u'my_key',
 u'private_network_id': u'xyz',
 u'volume_size': u'10',
 u'volume_type': u'ceph_fake'}

您不能在Spring对象上使用“new”关键字(Userdao userdao = new Userdaoimpl())。 您可以使用spring-boot注册Spring上下文,或者如果您有Web应用程序,则可以通过web.xml注册。

如果你想在main方法中使用你的dao。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
        classes = { HibernateConfig.class})
public class TestCaseApp {

    @Autowired
    @Qualifier("userDao")
    Userdao userdao;

    @Test
    public void testSessionFactory(){
         User user = new User();
         user.setAddress("New Delhi");
         user.setContact("9988776655");
         user.setEmail("komal@gmail.com");
         user.setEnabled(true);
         user.setName("Komal");
         user.setPassword("komal");
         user.setRole("CUSTOMER");
         userdao.add(user);
    }
}