gpt4 book ai didi

java - Hibernate + Mysql 创建sessionFactory失败

转载 作者:行者123 更新时间:2023-11-29 18:56:02 24 4
gpt4 key购买 nike

我在创建 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)
)
-->

最佳答案

关于java - Hibernate + Mysql 创建sessionFactory失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44133252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com