无法创建sessionFactory Hibernate + Mysql

时间:2017-05-23 11:16:26

标签: java mysql spring hibernate maven

我在创建sessionFactory对象时遇到问题。我正在使用Hibernate与Maven和Mysql。如何解决?

记录错误:

Failed to create sessionFactory object.org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
maj 23, 2017 1:03:39 PM org.springframework.web.context.support.XmlWebApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: pl.pawel112.webapp.UserDAO pl.pawel112.webapp.controllers.MainController.dao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO' defined in file [C:\Users\pawel\eclipse\workspace-ee\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\userapp\WEB-INF\classes\pl\pawel112\webapp\UserDAO.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [pl.pawel112.webapp.UserDAO]: Constructor threw exception; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:725)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4745)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5207)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

UserDAO.java文件(在src / main / pl / pawel112 / userapp中):

    package pl.pawel112.webapp;

import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Repository;

@Repository
public class UserDAO
{
    private static SessionFactory factory; 

    public void addUser(User user)
    {
    }

    public List<User> getUser()
    {
        return null;
    }

    public User getUserbyId(Integer id)
    {
        return null;
    }

    public UserDAO()
    {
        try
        {
            factory = new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex)
        { 
             System.err.println("Failed to create sessionFactory object." + ex);
             throw new ExceptionInInitializerError(ex); 
        }
    }
}

web.xml文件(在main / webapp / WEB-INF中):

<web-app id="WebApp_ID" version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Userdatabase</display-name>

    <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

applicationContext.xml(在main / webapp / WEB-INF中):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="pl.pawel112" />
    <context:annotation-config />
    <mvc:annotation-driven />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

MainController.java(在main / pl / pawel112 / webapp / controllers / MainController.java中):

package pl.pawel112.webapp.controllers;

import pl.pawel112.webapp.User;
import pl.pawel112.webapp.UserDAO;
import pl.pawel112.webapp.dataBase.DBLogin;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController
{

    @Autowired
    UserDAO dao;

    @RequestMapping("/list")
    public String listUser(Model model) {
        model.addAttribute("user", dao.getUser());
        return "list";
    }

    @RequestMapping("/add")
    public String addUser(HttpServletRequest request,  @ModelAttribute("DBLogin") @Valid DBLogin dbLogin, BindingResult result) {
        if (request.getMethod().equalsIgnoreCase("post") && !result.hasErrors()) {
            User user = new User();
            user.setLogin(dbLogin.getLogin());
            user.setEmail(dbLogin.getEmail());
            user.setPassword(dbLogin.getPassword());
            user.setGroup(dbLogin.getGroup());
            user.setAccount_blocked(dbLogin.isAccount_active());
            dao.addUser(user);
            return "redirect:/list";
        }
        return "add";
    }

    @RequestMapping("/user-{id}")
    public String getUser(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("user", dao.getUserbyId(id));
        return "user";
    }
}

hibernate.cfg.xml(在src / main / resources中):

<?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://127.0.0.1:3306/m1069_java_users
   </property>
   <property name="hibernate.connection.username">
      m1069_java_login
   </property>
   <property name="hibernate.connection.password">
      UNcXLTNALJVDc8MmQf39
   </property>

   <!-- List of XML mapping files -->
   <mapping resource="users.hbm.xml"/>

</session-factory>
</hibernate-configuration>

users.hbm.xml(在src / main / users.hbm.xml中):

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="users" table="users">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="login" column="login" type="string"/>
      <property name="email" column="email" type="string"/>
      <property name="password" column="password" type="string"/>
      <property name="account_blocked" column="account_blocked" type="boolean"/>
      <property name="group" column="id_group" type="int"/>
   </class>
</hibernate-mapping>

<!--
create table users (
   id INT NOT NULL auto_increment,
   login VARCHAR(50) default NULL,
   email  VARCHAR(50) default NULL,
   password VARCHAR(50) default NULL,
   account_blocked BOOLEAN default NULL,
   id_group INT default NULL,
   PRIMARY KEY (id)
)
-->

1 个答案:

答案 0 :(得分:0)