1

I'm learning spring mvc web with hibernate and maven.But I got this error.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.silwal.rentme.daoimpl.PersonDaoImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: class path resource [hibernate.cfg.xml] cannot be resolved to URL because it does not exist

servlet-context.xml file is here.

<!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.silwal.rentme,com.silwal.rentme.daoimpl" />


    <!-- DataSource for JDBC connection -->
    <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </beans:bean>


    <!-- Hibernate 4 SessionFactory Bean -->
    <beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        <beans:property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </beans:bean>


    <!-- Transaction Manager to make Transaction Support -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory" />
    </beans:bean>


     <beans:bean id="personDao" class="com.silwal.rentme.daoimpl.PersonDaoImpl">
        <beans:constructor-arg>
            <beans:ref bean="sessionFactory" />
        </beans:constructor-arg>
    </beans:bean>

Person entity class for database relation mapping class is here.

package com.silwal.rentme.entity;

import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "person_info")
public class Person {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "middle_name")
    private String middleName;
    @Column(name = "last_name")
    private String lastName;

    public Person() {

    }
    public Person(String firstName,String middleName,String lastName) {
        this.firstName=firstName;
        this.middleName=middleName;
        this.lastName=lastName;
    }
    public Long getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    @Override
    public String toString() {
        return "Person[firstName="+firstName+",middleName="+middleName+",lastName="+lastName+"]";
    }

}

PersonDao Interface class is here.

  package com.silwal.rentme.dao;
import java.util.List;
import com.silwal.rentme.entity.Person;
public interface PersonDao {
     //List<Person> listAllPerson();
     void savePerson(Person person);
}

PersonDao Implementation class is here.

package com.silwal.rentme.daoimpl;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.silwal.rentme.dao.PersonDao;
import com.silwal.rentme.entity.Person;

@Component
public class PersonDaoImpl implements PersonDao {

    @Autowired
    private SessionFactory sessionFactory;

    public PersonDaoImpl() {

    }
    public PersonDaoImpl(SessionFactory sessionFactory) {
        this.sessionFactory=sessionFactory;
    }

    @Override
    @Transactional
    public void savePerson(Person person) {
        sessionFactory.getCurrentSession().save(person);
    }

}

HomeController class is here.

package com.silwal.rentme.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.silwal.rentme.daoimpl.PersonDaoImpl;
import com.silwal.rentme.entity.Person;


/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
    @Autowired
     PersonDaoImpl personDao;   
    private Person person;
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);
        person=new Person("bisho", "", "silwal");
        personDao.savePerson(person);
        return "home";
    }

}

hibernate.cfg.xml class is here.

 <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </property>
        <property name="hibernate.connection.driver_class">
            com.mysql.jdbc.Driver
        </property>

        <!-- Assume test is the database name -->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/rentme</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.connection.show_sql">true</property>
        <property name="hibernate.connection.hbm2ddl.auto">create</property>
        <mapping class="com.silwal.rentme.entity.*" />
    </session-factory>
</hibernate-configuration>

How can I fix this?

Nitish Kumar Diwakar
  • 663
  • 4
  • 14
  • 25
Bisho Silwal
  • 121
  • 1
  • 9
  • 3
    Error seems to suggest your hibernate.cfg.xml file is either missing or not included in your classpath. Where in your application is this file? – Plog Aug 04 '17 at 10:09
  • Its inside WEB-INF folder. – Bisho Silwal Aug 04 '17 at 10:09
  • I see lately a lot of people having problems with Spring MVC configurations. For that purpose Spring Boot was invented by Spring team. I would suggest to try that out. And btw, you don't have to implement your DAO interface, you can extend it from interfaces like CrudRepository or JpaRepository, or even MongoRepository which already have implementations for common CRUD operations on DB. – GarRudo Aug 04 '17 at 10:18
  • @GarRudo yes i have heard spring Boot but i didnt try it .Well if it is worth to learn spring boot then i will definitely try it out.Thanks for suggestion. – Bisho Silwal Aug 04 '17 at 10:23
  • @bisho It is definitely worth it, you will be surprised how much easier it is to develop on Boot than Spring MVC. You can build what you try there in about 5-10 min without have to configuring any XML. – GarRudo Aug 04 '17 at 10:27
  • @GarRudo owo 5-10 min really . Then I must try . – Bisho Silwal Aug 04 '17 at 10:30
  • @bisho This one would be what you need: https://spring.io/guides/gs/serving-web-content/ . Link from earlier will be a bit confusing for now. – GarRudo Aug 04 '17 at 10:32

1 Answers1

0

Just having your hibernate.cfg.xml file in your WEB-INF folder is not enough to ensure it's on the classpath. Have a look at this related question on where to put this file:

Location of hibernate.cfg.xml in project?

My suggestion would be to create a resources folder and include it in there.

Plog
  • 9,164
  • 5
  • 41
  • 66
  • actually I have already tried putting hibernate.cfg.xml file inside resources/WEB-INF but still didnt work. – Bisho Silwal Aug 04 '17 at 10:31
  • 1
    @bisho No I said it shouldn't be in WEB-INF. Put it in src/main/resources and make sure that folder is marked as a classpath resource. – Plog Aug 04 '17 at 10:36
  • how can i marked that folder as a classpath resource? – Bisho Silwal Aug 04 '17 at 11:39
  • @bisho depends on your IDE in intelliJ you can just right click the folder and go Mark Directory As > Resources Root – Plog Aug 04 '17 at 11:54