2017-04-07 291 views
0

運行用SpringMVC/Hibernate的CRUD我是新進春/休眠,試圖建立使用用SpringMVC /休眠按照本教程一個簡單的CRUD: https://www.youtube.com/watch?v=zKVYjJjNSak無法在本地主機

每次我在我的Tomcat 7上運行這個程序服務器,我得到以下警告:

Apr 07, 2017 3:38:16 AM org.hibernate.engine.jdbc.internal.JdbcServicesImpl configure WARN: HHH000342: Could not obtain connection to query metadata : No suitable driver found for jdbc.url

什麼,我得到我的瀏覽器:

HTTP Status 500 - Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Could not open connection

當我輸入網址

http://localhost:8080/SpringMVCHibernateExample/customer/list

,當我進入這些網址,我得到以下警告:在控制檯

我:

WARN: SQL Error: 0, SQLState: 08001 Apr 07, 2017 11:16:50 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: No suitable driver found for jdbc.url Apr 07, 2017 11:16:50 AM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/SpringMVCHibernateExample] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Could not open connection] with root cause java.sql.SQLException: No suitable driver found for jdbc.url at java.sql.DriverManager.getConnection(DriverManager.java:689) at java.sql.DriverManager.getConnection(DriverManager.java:208) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139) at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171) at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450) at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) at com.sun.proxy.$Proxy25.listAllCustomers(Unknown Source) at springmvc_example.controller.CustomerController.list(CustomerController.java:26) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)

Apr 07, 2017 11:17:16 AM org.springframework.web.servlet.PageNotFound noHandlerFound WARNING: No mapping found for HTTP request with URI [/SpringMVCHibernateExample/] in DispatcherServlet with name 'dispatcher' Apr 07, 2017 11:19:43 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN: SQL Error: 0, SQLState: 08001 Apr 07, 2017 11:19:43 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: No suitable driver found for jdbc.url Apr 07, 2017 11:19:43 AM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/SpringMVCHibernateExample] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Could not open connection] with root cause java.sql.SQLException: No suitable driver found for jdbc.url at java.sql.DriverManager.getConnection(DriverManager.java:689) at java.sql.DriverManager.getConnection(DriverManager.java:208) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153) at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155) at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120) at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139) at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228) at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:171) at org.hibernate.internal.SessionImpl.connection(SessionImpl.java:450) at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:450) at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373) at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:427) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) at com.sun.proxy.$Proxy25.listAllCustomers(Unknown Source) at springmvc_example.controller.CustomerController.list(CustomerController.java:26) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:218) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)

我與問題爭取5-6小時(兩天在我與這個項目中的其他問題鬥爭之前 - 我已經修復了這個問題,而不是在stackoverflow的幫助下進行最後的回合)。誰能幫我?

我的pom.xml的是:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>springmvc_example</groupId> 
    <artifactId>SpringMVCHibernateExample</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>war</packaging>  
    <dependencies> 
    <dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-webmvc</artifactId> 
    <version>4.3.0.RELEASE</version>  
    </dependency> 
    <dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-tx</artifactId> 
    <version>4.3.0.RELEASE</version>  
    </dependency> 
    <dependency> 
    <groupId>javax.servlet</groupId> 
    <artifactId>jstl</artifactId> 
    <version>1.2</version>  
    </dependency> 
    <dependency> 
    <groupId>javax.servlet</groupId> 
    <artifactId>javax.servlet-api</artifactId> 
    <version>3.1.0</version>  
    </dependency>   
    <dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-jdbc</artifactId> 
    <version>4.3.0.RELEASE</version>  
    </dependency> 
    <dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-orm</artifactId> 
    <version>4.3.0.RELEASE</version>  
    </dependency> 
    <dependency> 
    <groupId>mysql</groupId> 
    <artifactId>mysql-connector-java</artifactId> 
    <version>5.1.6</version> 
</dependency>   
    <dependency> 
    <groupId>org.hibernate</groupId> 
    <artifactId>hibernate-core</artifactId> 
    <version>4.3.10.Final</version>  
    </dependency>   
    <dependency> 
    <groupId>javax.validation</groupId> 
    <artifactId>validation-api</artifactId> 
    <version>1.1.0.Final</version>  
    </dependency> 
    </dependencies> 
<build> 
    <plugins> 
     <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-war-plugin</artifactId> 
      <version>2.6</version> 
      <configuration> 
       <warSourceDirectory>src/main/webapp</warSourceDirectory> 
       <failOnMissingWebXml>false</failOnMissingWebXml> 
      </configuration> 
     </plugin> 
    </plugins> 
</build> 

這是我的config.properties:

jdbc.driverClassName = com.mysql.jdbc.Driver 
jdbc.url = jdbc:mysql://localhost:3306/springmvc/ 
jdbc.dialect=org.hibernate.dialect.MySQLDialect 

jdbc.username=root 
jdbc.password=nandri 
hibernate.show_sql=true 
hibernate.format_sql = false 
javax.persistence.validation.mode=none 

我HibernateConfig.java類:

package springmvc_example.config; 

import java.util.Properties; 

import javax.sql.DataSource; 


import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.context.annotation.PropertySource; 
import org.springframework.core.env.Environment; 
import org.springframework.jdbc.datasource.DriverManagerDataSource; 
import org.springframework.orm.hibernate4.HibernateTransactionManager; 
import org.springframework.orm.hibernate4.LocalSessionFactoryBean; 
import org.springframework.transaction.annotation.EnableTransactionManagement; 
import org.springframework.web.servlet.config.annotation.EnableWebMvc; 



@Configuration 
@EnableWebMvc 
@EnableTransactionManagement 
@ComponentScan({"springmvc_example.config"}) 
@PropertySource(value = {"classpath:config.properties"}) 
public class HibernateConfig { 

    @Autowired 
    private Environment environment; 


    @Bean 
    public LocalSessionFactoryBean sessionFactory() { 
     LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 
     sessionFactory.setDataSource(dataSource()); 
     sessionFactory.setPackagesToScan(new String[] { "springmvc_example.model" }); 
     sessionFactory.setHibernateProperties(hibernateProperties()); 
     return sessionFactory; 
    } 

    @Bean 
    public DataSource dataSource() { 

     DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); 
     dataSource.setUrl("jdbc.url"); 
     dataSource.setUsername("jdbc.username"); 
     dataSource.setPassword("jdbc.password"); 
     return dataSource; 
    } 

    private Properties hibernateProperties() { 

     Properties properties = new Properties(); 
     properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); 
     properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql")); 
     properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql")); 


     return properties; 
    } 


    @Bean 
    @Autowired 
    public HibernateTransactionManager transactionManager(
      SessionFactory s) { 
     HibernateTransactionManager txManager = new HibernateTransactionManager(
       s); 
     return txManager; 
    } 



} 

WebConfig .java:

package springmvc_example.config; 

import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.web.servlet.config.annotation.EnableWebMvc; 
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; 
import org.springframework.web.servlet.view.InternalResourceViewResolver; 
import org.springframework.web.servlet.view.JstlView; 

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = "springmvc_example") 
public class WebConfig extends WebMvcConfigurerAdapter{ 


    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry){ 
     registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 

} 


    @Bean 
    public InternalResourceViewResolver viewResolver(){ 
     InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); 
     viewResolver.setViewClass(JstlView.class); 
     viewResolver.setPrefix("/WEB-INF/jsp/"); 
     viewResolver.setSuffix(".jsp"); 
     return viewResolver; 
    } 



} 

WebInitializer.java:

package springmvc_example.config; 

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; 

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 

     return new Class[]{WebConfig.class}; 
    } 

    @Override 
    protected Class<?>[] getServletConfigClasses() { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    @Override 
    protected String[] getServletMappings() { 

     return new String[]{"/"}; 
    } 

} 

我的模型類 - Customer.java

package springmvc_example.model; 

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="customer") 
public class Customer { 

    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private int id; 
    @Column(name="firstname") 
    private String firstname; 
    @Column(name="lastname") 
    private String lastname; 
    @Column(name="gender") 
    private String gender; 
    @Column(name="address") 
    private String address; 
public int getId() { 
    return id; 
} 
public void setId(int id) { 
    this.id = id; 
} 
public String getFirstname() { 
    return firstname; 
} 
public void setFirstname(String firstname) { 
    this.firstname = firstname; 
} 
public String getLastname() { 
    return lastname; 
} 
public void setLastname(String lastname) { 
    this.lastname = lastname; 
} 
public String getGender() { 
    return gender; 
} 
public void setGender(String gender) { 
    this.gender = gender; 
} 
public String getAddress() { 
    return address; 
} 
public void setAddress(String address) { 
    this.address = address; 
} 
} 

DAO - CustomerDao.java:

package springmvc_example.dao; 

import java.util.List; 

import springmvc_example.model.Customer; 

public interface CustomerDao { 
    public List<Customer> listAllCustomers(); 

    public void saveOrUpdate(Customer customer); 

    public Customer findCustomerById(int id); 
    void deleteCustomer(int id); 
} 

DAO實現 - CustomerDaoImpl。 java:

package springmvc_example.dao; 

import java.util.List; 

import org.hibernate.Criteria; 
import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 

import springmvc_example.model.Customer; 
@Repository 
public class CustomerDaoImpl implements CustomerDao { 

    @Autowired 
    private SessionFactory sessionFactory; 

    private org.hibernate.Session getSession(){ 
     return sessionFactory.getCurrentSession(); 
    } 

    @SuppressWarnings("unchecked") 
    public List<Customer> listAllCustomers() { 
     // Create CriteriaBuilder 
     //CriteriaBuilder builder = getSession().getCriteriaBuilder(); 

     // Create CriteriaQuery 
     //CriteriaQuery<Customer> criteria = builder.createQuery(Customer.class); 
     Criteria criteria = getSession().createCriteria(Customer.class); 
     return (List<Customer>) ((Criteria) criteria).list(); 
    } 

    public void saveOrUpdate(Customer customer) { 
     getSession().saveOrUpdate(customer); 

    } 

    public Customer findCustomerById(int id) { 
     Customer customer = (Customer) getSession().get(Customer.class, id); 
     return customer; 
    } 

    public void deleteCustomer(int id) { 
     Customer customer = (Customer) getSession().get(Customer.class, id); 
     getSession().delete(customer); 
    } 

} 

控制器 - CustomerController.java:

package springmvc_example.controller; 

import java.util.List; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 
import org.springframework.web.servlet.ModelAndView; 

import springmvc_example.model.Customer; 
import springmvc_example.service.CustomerService; 

@Controller 
@RequestMapping(value="/customer", method=RequestMethod.GET) 
public class CustomerController { 
    @Autowired 
    CustomerService customerService; 

    @RequestMapping(value="/list", method=RequestMethod.GET) 
    public ModelAndView list(){ 
     ModelAndView model = new ModelAndView("customer/list"); 

     List<Customer> list = customerService.listAllCustomers(); 
     model.addObject("list", list); 
     return model; 
    } 


    @RequestMapping(value="/update/{id}", method=RequestMethod.GET) 
    public ModelAndView update(@PathVariable("id") int id){ 
     ModelAndView model = new ModelAndView("customer/form"); 
     Customer customer = customerService.findCustomerById(id); 

     model.addObject("customerForm", customer); 
     return model; 
    } 



    @RequestMapping(value="/add", method=RequestMethod.GET) 
    public ModelAndView add(){ 
     ModelAndView model = new ModelAndView("customer/form"); 
     Customer customer = new Customer(); 

     model.addObject("customerForm", customer); 
     return model; 
    } 

    @RequestMapping(value="/save", method=RequestMethod.POST) 
    public ModelAndView save(@ModelAttribute("customerForm") Customer customer){ 
     customerService.saveOrUpdate(customer); 
     return new ModelAndView("redirect:/customer/list"); 
    } 

} 

項目的結構如下:pom.xml的是

C:\Users\Jeddid\workspace\SpringMVCHibernateExample

JSP在:

C:\Users\Jeddid\workspace\SpringMVCHibernateExample\src\main\webapp\WEB-INF\jsp\customer

config.properties在

C:\Users\Jeddid\workspace\SpringMVCHibernateExample\src\main\resources

HibernateConfig.java,WebConfig。java和WebInitializer.java是

C:\Users\Jeddid\workspace\SpringMVCHibernateExample\src\main\java\springmvc_example\config

和的.java類的其餘部分都在相應的文件夾(iemodel是

C:\Users\Jeddid\workspace\SpringMVCHibernateExample\src\main\java\springmvc_example\model

, 控制器處於

C:\Users\Jeddid\workspace\SpringMVCHibernateExample\src\main\java\springmvc_example\controller

,CustomerService.java和CustomerServiceImpl.java正在服務等)

回答

0

錯誤說:

No mapping found for HTTP request with URI [/SpringMVCHibernateExample/customer]

那是因爲,你把它映射到/客戶/列表,你應該嘗試

http://localhost:8080/SpringMVCHibernateExample/customer/list 

Update:

回答你的問題在評論 改變你jdbc.url以下幾點:

(1) remove/at the end (2) remove the spaces before and after =

jdbc.url=jdbc:mysql://localhost:3306/springmvc 
+0

我更新ŧ他提出的 – NiHao92

+0

提議的更改(刪除/和空格)沒有給出任何結果 – NiHao92