0

Hi I try to add data to oraclexe database with spring mvc and hibernate by dao design pattern but it make this error "org.springframework.web.util.NestedServletException" how can solve this problem ?

This program just worked with springMVC whithout hibernate but when I try to add hibernate it doesn't work and give me the error I don't know how can connect springMVC with hibernate

this is my pom.xml

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc14</artifactId>
      <version>10.2.0.4.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.4.1.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
        <version>3.5.6-Final</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.5</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.25</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>

  </dependencies>

and class Resource.java

package com.spring.mvc.model;

import javax.persistence.*;

@Entity
@Table(name = "RESOURCSE")
public class Resource {
    @Id
    @GeneratedValue
    @Column(name = "ID",unique = true,length = 10)
    private int id;
    @Column(name = "NAME", length = 25)
    private String name;
    @Column(name = "TYPE", length = 30)
    private String type;
    @Column(name = "unitOfMesure", length = 25)
    private String unitOfMesure;
    @Column(name = "notes", length = 25)
    private String notes;

    public int getId() {
        return id;
    }

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

    public String getNotes() {
        return notes;
    }

    public void setNotes(String notes) {
        this.notes = notes;
    }

    public Resource(String name, String type, String unitOfMesure, String notes) {
        this.name = name;
        this.type = type;
        this.unitOfMesure = unitOfMesure;
        this.notes = notes;
    }

    public String getUnitOfMesure() {
        return unitOfMesure;
    }

    public void setUnitOfMesure(String unitOfMesure) {
        this.unitOfMesure = unitOfMesure;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Resource() {
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Resource{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                ", unitOfMesure='" + unitOfMesure + '\'' +
                ", notes='" + notes + '\'' +
                '}';
    }
}

and ResourceDaoImpl

package com.spring.mvc.dao;

import com.spring.mvc.model.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Repository
@Transactional
public class ResourceDaoImpl implements ResourceDao {



    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void addResource(Resource resource) {
        try (Session session = this.sessionFactory.getCurrentSession()) {
            session.persist(resource);
        }

    }

    @Override
    public void updateResource(Resource resource) {
        Session session = this.sessionFactory.getCurrentSession();
        session.update(resource);

    }

    @Override
    public List<Resource> listResource() {
        Session session = this.sessionFactory.getCurrentSession();
        List list_resources = session.createQuery("from Resource ").list();
        return list_resources;
    }

    @Override
    public Resource getResourceById(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        Resource resourceId = session.load(Resource.class, id);
        return resourceId;
    }

    @Override
    public void removeResource(int id) {
        Session session = this.sessionFactory.getCurrentSession();
        Resource resourceId = session.load(Resource.class, id);
        if (resourceId != null){
            session.delete(resourceId);
        }

    }
}

and ResourceServiceImpl

package com.spring.mvc.service;

import com.spring.mvc.dao.ResourceDao;
import com.spring.mvc.model.Resource;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@Transactional
public class ResourceServiceImpl implements ResourceService {


    private ResourceDao resourceDao;

    public ResourceDao getResourceDao() {
        return resourceDao;
    }

    public void setResourceDao(ResourceDao resourceDao) {
        this.resourceDao = resourceDao;
    }

    @Override
    public void addResource(Resource resource) {
        this.resourceDao.addResource(resource);

    }

    @Override
    public void updateResource(Resource resource) {
        this.resourceDao.updateResource(resource);

    }

    @Override
    public List<Resource> listResource() {
        return this.resourceDao.listResource();
    }

    @Override
    public Resource getResourceById(int id) {
        return this.resourceDao.getResourceById(id);
    }

    @Override
    public void removeResource(int id) {

        this.resourceDao.removeResource(id);
    }
}

and ResourceController

package com.spring.mvc.controller;

import com.spring.mvc.model.Resource;
import com.spring.mvc.service.ResourceService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

@Controller
@RequestMapping("/resource")
public class ResourceController {
    private ResourceService resourceService;

    public void setResourceService(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model){
        return "resource_add";
    }

    @ModelAttribute("resource")
    public Resource resource(){
        return new Resource();
    }

    @ModelAttribute("typeOptions")
    public List<String> getTypes(){
        return new LinkedList<>(Arrays.asList(new String[]{
                "English","France","Italy"
        }));
    }

    @ModelAttribute("radioOptions")
    public List<String> getRadios(){
        return new LinkedList<>(Arrays.asList(new String[]{
                "Hour","Piece","Tones"
        }));
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@ModelAttribute Resource resource){

        this.resourceService.addResource(resource);
        System.out.println(resource);
        return "resource_add";
    }
}

and this is my hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/xsd/hibernate-configuration">
<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="connection.username">username</property>
        <property name="connection.password">password</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle12cDialect</property>
        <mapping class="com.spring.mvc.model.Resource"></mapping>
    </session-factory>
</hibernate-configuration>

Soraya
  • 13
  • 7

1 Answers1

0

First do not put @Transactional in front of DAO classes, put it only above the Services classes.it won't be an error but it is a good practice

Edit you did not add the hibernate in your spring-mvc, that's why @Autowired was not worked. you need to add hibernate config inside the spring like this (this is an example code, and change your appropriate values)

 <!-- Add support for component scanning -->
    <context:component-scan base-package="net.javaguides.springmvc" />
    <!-- Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven />
    <!-- Define Spring MVC view resolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- Step 1: Define Database DataSource / connection pool -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test?useSSL=false&amp;serverTimezone=UTC" />
        <property name="user" value="user" />
        <property name="password" value="password" />   
    </bean>
    <!-- Step 2: Setup Hibernate session factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="net.javaguides.springmvc.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <!-- Step 3: Setup Hibernate transaction manager -->
    <bean id="myTransactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="myTransactionManager" />
    <!-- Add support for reading web resources: css, images, js, etc ... -->
    <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>

/********************************************************************/

in this method

@Override
public void updateResource(Resource resource) {
    Session session = this.sessionFactory.getCurrentSession();
    session.update(resource);

}

use beginTransaction and commit, like this

@Override
public void updateResource(Resource resource) {
    Session session = this.sessionFactory.getCurrentSession();
    session.beginTransaction();
    session.update(resource);
    session.getTransaction().commit();

}

and I am not sure you initialize the sessionFactory here

private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
    return sessionFactory;
}

you can simply initialize using @Autowired annotation. like that,

@Autowired
protected SessionFactory sessionFactory;
majurageerthan
  • 2,169
  • 3
  • 17
  • 30
  • if it is not working, please put your full error log in question – majurageerthan Apr 04 '19 at 04:25
  • Hi thanks for your help when I add @Autowired give this error "Could not autowire. No beans of 'SessionFactory' type found." and I don't know how could solve also when I add bean tag in applicationContext also not solve – Soraya Apr 04 '19 at 07:08
  • it means you did not initialize hibernate with spring. could you show me the xml file which initializes the hibernate into the spring? – majurageerthan Apr 04 '19 at 07:23
  • if possible, give these files git repo url... i need to check your whole config files – majurageerthan Apr 04 '19 at 07:25
  • you do not need hibernate.cfg.xml file if you config spring with hibernate, please refer this tutorial (http://websystique.com/spring/spring4-hibernate4-mysql-maven-integration-example-using-annotations/) – majurageerthan Apr 04 '19 at 07:33
  • @Soraya you can post your GitHub URL, moreover, you did not do the proper config. post your spring-mvc config file – majurageerthan Apr 04 '19 at 07:37
  • I test tutorial but also give error and I have another question "when I use springMVC in web.xml and dispatcher-servlet and applicationContext which code need to add with those step tutorial link?" – Soraya Apr 04 '19 at 09:50
  • I could not understand your question – majurageerthan Apr 04 '19 at 09:58
  • sorry my english language is not good those tutorial link is for spring with hibernate I want to use spring-mvc and I don't know where is my problem and which training need for better learning – Soraya Apr 04 '19 at 10:10
  • ok got it, give me some time(within tomorrow) I will find the best tutorial for you or I will write an article for you – majurageerthan Apr 04 '19 at 10:17
  • 1
    wow thanks I learn spring mvc and hibernate seprately but can't join these for create webapp – Soraya Apr 04 '19 at 10:26
  • here is the best link, there are many examples and you can download the source code also, let me know if you struck in anywhere (https://github.com/RameshMF/spring-mvc-tutorial) – majurageerthan Apr 05 '19 at 03:12
  • Thanks, I'll do it as soon as possible and I'll be back – Soraya Apr 05 '19 at 06:15
  • hi I'm back I add your config code in dispatcher-servlet.xml but the datasource tag property don't resolve and this error show for example for property tag for datasource in name attribute such driverClass show this error: "Cannot resolve property 'driverClass' less... (Ctrl+F1) Inspection info:Spring XML model validation" – Soraya Apr 06 '19 at 17:30
  • in this code : – Soraya Apr 06 '19 at 17:31
  • yes this is zip file for my project : " http://s9.picofile.com/file/8356768584/springmvc5_hibernate5_jsp_oracle_example.zip.html " – Soraya Apr 07 '19 at 15:19
  • org.hibernate hibernate-c3p0 ${hibernate.version} add this dependency in your maven pom.xml – majurageerthan Apr 07 '19 at 15:36
  • thanks I add this and resolved but this error show :" Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml] " – Soraya Apr 08 '19 at 03:08
  • I am not using oracle web server, that's why i am unable to run your code, wait i will find a solution to you – majurageerthan Apr 08 '19 at 03:25
  • first delete these codes " Archetype Created Web Application org.springframework.web.context.ContextLoaderListener contextConfigLocation /WEB-INF/applicationContext.xml " from web.xml – majurageerthan Apr 08 '19 at 05:19
  • and delete "applicationContext.xml" file in your "src/main/webapp/WEB-INF" and run your app again and tell me the error details – majurageerthan Apr 08 '19 at 05:23
  • also show me this error :" Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml] " – Soraya Apr 08 '19 at 05:27
  • did you delete these " Archetype Created Web Application org.springframework.web.context.ContextLoaderListener contextConfigLocation /WEB-INF/applicationContext.xml " from web.xml – majurageerthan Apr 08 '19 at 05:38
  • then restore those files and delete these lines " " in applicationContext.xml – majurageerthan Apr 08 '19 at 06:12
  • sorry also same error this is new link of my project : " http://s9.picofile.com/file/8356813076/springmvc5_hibernate5_jsp_oracle_example.zip.html " please see this thanks – Soraya Apr 08 '19 at 06:50
  • I am busy right now, I'll see it later... sorry for the inconvenience – majurageerthan Apr 08 '19 at 06:58
  • your last sent project is working fine for me except database (because I don't have Oracle), I think, you are using Eclipse to run the code, the problem may be of Eclipse IDE (I am using InteliJ Idea). create a war file using "mvn clean install" and deploy it in Tomcat. it should work now – majurageerthan Apr 08 '19 at 16:12
  • thanks for your response I use IntelliJ too ,I try your help and back – Soraya Apr 08 '19 at 16:41
  • also same problem this is my log " http://s9.picofile.com/file/8356869800/log.txt.html " – Soraya Apr 08 '19 at 16:47
  • I am wondering, why did you have these error when i do not have any errors for the same code? Could you tell me your Java version? – majurageerthan Apr 08 '19 at 17:04
  • yeah me too , I use jdk-11.0.2 and jre1.8.0_201 and apache-maven-3.6.0 and Tomcat 9.0.13 – Soraya Apr 08 '19 at 17:12
  • use this war file and run it, https://drive.google.com/file/d/1BdQE_pst5-Ys3WEeC-zi4sVEA_WIQsXm/view?usp=sharing – majurageerthan Apr 08 '19 at 17:15
  • Wait... I'll send my code... You compile it and run it – majurageerthan Apr 08 '19 at 17:30
  • Hi @majuran , I have new question can you help me? And I don't know how can I send my question to you? – Soraya Jun 24 '19 at 08:24