0

Hibernate configure using java @Bean annotation

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

Main method:

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

Exception stack trace:

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

Anyone please help I m already start transaction using @Repository("userDao") @Transactional

I'm also try to run on junit but still get same error!!

0

2 Answers 2

1

You have contructed User and Userdaoimpl only in your main method! Question yourself that how the SessionFactory and other @Beans would be initilized?

Try to run the application through spring context or as a spring boot application. Then get userdao Bean to invoke add method.

Sign up to request clarification or add additional context in comments.

Comments

0

You should register your context like that, if you would like to try your app in a JUnit test:

@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("[email protected]"); user.setEnabled(true); user.setName("Komal"); user.setPassword("komal"); user.setRole("CUSTOMER"); userdao.add(user); } } 

You can't use "new" keyword (Userdao userdao = new Userdaoimpl()) on a Spring object. You can register Spring context with spring-boot or if you have a web application, then via the web.xml.

If you would like to use your dao in the main method.

ApplicationContext ctx = new AnnotationConfigApplicationContext(HibernateConfig.class); Userdao userdao = ctx.getBean("userDao",Userdao.class); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.