how to reach dao from @Component class which is implementing CommandLineRunner

时间:2017-07-12 08:08:23

标签: hibernate jpa spring-boot

I need your help.

I want to load initial data to database. For this I get one parameter from commandline. If this parameter is init programme start to load initial data(for e.g. create a default admin user on database) use daos. Bu I got this error.

Caused by: org.hibernate.HibernateException: No CurrentSessionContext configured!

Here is my pom.xml

<dependencies>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <!-- do you like thymeleaf? -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!-- optional, it brings userful tags to display spring security stuff -->
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>

    <!-- hot swapping, disable cache for template, enable live reload -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>


    <!-- Optional, for bootstrap -->
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.7</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jetty</artifactId>
    </dependency>


    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>

    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>

    <dependency>
        <groupId>org.jadira.usertype</groupId>
        <artifactId>usertype.core</artifactId>
        <version>5.0.0.GA</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-neo4j</artifactId>
        <exclusions>
        <exclusion>
            <groupId>javax.persistence</groupId>
            <artifactId>com.springsource.javax.persistence</artifactId>
        </exclusion>
        </exclusions>
    </dependency>

</dependencies>

<build>
    <plugins>
        <!-- Package as an executable jar/war -->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

Here is my loading initial data component:

@Component
public class InitialiazeInsert implements CommandLineRunner {

    @Inject
    UserDao userDao;

    @Override
    public void run(String... args) throws Exception {
        String initializeParam = args[0];
        if (initializeParam.equals("init")) {
            Scanner kb = new Scanner(System.in);
            System.out.println("Please insert password of default" +
                    " helpcenter@mts.io user");
            String defPassword = kb.next();

            User user = new User();
            user.setEmail("helpcenter@mts.io user");
            user.setPassword(defPassword);
            user.setActive(true);
            user.setName("helpcenter@mts.io user");
            user.setSurname("helpcenter@mts.io user");
            user.setCreatedDate(new Date(System.currentTimeMillis()));
            user.setRole(Role.ADMIN);

            user = userDao.create(user);
        }
    }
}

Here is UserDao:

@Repository
public class UserDao extends BaseDao<User>{

    @Inject
    public UserDao(EntityManagerFactory entityManagerFactory) {
        super(entityManagerFactory);
    }

    public Optional<User> findByUsername(String userName){
        Criteria criteria = currentSession().createCriteria(User.class);
        criteria.add(Restrictions.eq("email",userName));
        return Optional.ofNullable(uniqueResult(criteria));
    }

    public List<User> findByRole(Role role){
        Criteria criteria = currentSession().createCriteria(User.class);
        criteria.add(Restrictions.eq("role",role));
        List<User> users = criteria.list();
        return users;
    }

    public Optional<User> changePassword(String userName,String newPassword){
        Optional<User> user = findByUsername(userName);

        if(user.isPresent()){
            user.get().setPassword(newPassword);
            persist(user.get());
        }

        return user;
    }
}

Here is BaseDao:

public class BaseDao<T extends BaseEntity> extends AbstractDao<T> {

    @Inject
    public BaseDao(EntityManagerFactory entityManagerFactory) {
        super(entityManagerFactory);
    }

    public <E> List<E> findAll(Class<? extends BaseEntity> clazz){

        Criteria criteria = currentSession().createCriteria(clazz);
        List<E> list = criteria.list();
        return list;
    }

    public T findById(Serializable oid) {
        return get(oid);
    }

    @SuppressWarnings("unchecked")
    public T findById(Class<? extends BaseEntity> clazz, Serializable oid){
        return (T) currentSession().get(clazz,requireNonNull(oid));
    }

    public T create(T entity){
        return persist(entity);
    }

    public T update(T entity){
        return persist(entity);
    }

    public T delete(T entity){
        currentSession().delete(entity);
        return entity;
    }

    public void flush(){
        currentSession().flush();
    }

    @SuppressWarnings("unchecked")
    public T merge(T entity) {
        return (T) currentSession().merge(entity);
    }

    public T detach(T entity){
        currentSession().evict(entity);
        return entity;
    }
}

Here is AbstractDao:

public class AbstractDao<E> {

    private final SessionFactory sessionFactory;

    private final Class<?> entityClass;

    private final EntityManager entityManager;


    public AbstractDao(EntityManagerFactory entityManagerFactory){
        this.sessionFactory = requireNonNull(
                entityManagerFactory.unwrap(SessionFactory.class));
        entityManager = entityManagerFactory.createEntityManager();
        this.entityClass = Generics.getTypeParameter(getClass());
    }

    protected Session currentSession(){
        return sessionFactory.getCurrentSession();
    }

    protected Criteria criteria(){
        return currentSession().createCriteria(entityClass);
    }

    protected CriteriaQuery<E> criteriaQuery(){
        return entityManager.getCriteriaBuilder().createQuery(getEntityClass());
    }

    protected Query namedQuery(String queryName) throws HibernateException{
        return currentSession().getNamedQuery(requireNonNull(queryName));
    }


    @SuppressWarnings("unchecked")
    public Class<E> getEntityClass() {
        return (Class<E>) entityClass;
    }


    @SuppressWarnings("unchecked")
    protected E uniqueResult(Criteria criteria) throws HibernateException{
        return (E) requireNonNull(criteria).uniqueResult();
    }

    protected E uniqueResult(Query query) throws HibernateException{
        return (E) requireNonNull(query).uniqueResult();
    }

    @SuppressWarnings("unchecked")
    protected List<E> list(Criteria criteria) throws HibernateException{
        return requireNonNull(criteria).list();
    }


    @SuppressWarnings("unchecked")
    protected E get(Serializable id) {
        return (E) currentSession().get(entityClass, requireNonNull(id));
    }

    protected E persist(E entity) throws HibernateException{
        currentSession().saveOrUpdate(requireNonNull(entity));
        return entity;
    }

    protected <T> T initialize(T proxy) throws HibernateException{
        if(!Hibernate.isInitialized(proxy)){
            Hibernate.initialize(proxy);
        }

        return proxy;
    }
}

Here is HibernateConfig class:

@Configuration
@EnableTransactionManagement
public class HibernateConfig {

@Inject
HibernateParams hibernateParams;

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
    LocalContainerEntityManagerFactoryBean em =
            new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[]{"io.mts.helpcenter.hibernate"});

    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());

    return em;
}

@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(hibernateParams.getDriverClassName());
    dataSource.setUrl(hibernateParams.getUrl());
    dataSource.setUsername( hibernateParams.getUsername() );
    dataSource.setPassword( hibernateParams.getPassword());
    return dataSource;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);

    return transactionManager;
}

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
    return new PersistenceExceptionTranslationPostProcessor();
}

public Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", hibernateParams.getDdlAuto());
    properties.setProperty("hibernate.dialect", hibernateParams.getDialect());
    properties.setProperty("hibernate. current_session_context_class",
    "org.springframework.orm.hibernate5.SpringSessionContext");
    return properties;
}

@Bean
public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf){

    return hemf.getSessionFactory();
}
}

Where am I wrong? Could you help me please?

0 个答案:

没有答案