Eclipse Spring Bean创建错误

时间:2015-12-17 03:15:54

标签: java eclipse spring hibernate spring-mvc

我正在尝试使用spring hibernate和jsp运行一个简单表单注册的示例代码。但是,当我尝试在eclipse中运行代码时,我收到以下错误。谢谢您的帮助!

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'con' defined in class path resource [config/spring-hibernate.xml]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at com.student.dao.StudentDaoImpl.addStudent(StudentDaoImpl.java:27)
    at com.student.controller.RegisterServlet.doPost(RegisterServlet.java:57)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    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:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ExceptionInInitializerError
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
    ... 31 more
Caused by: org.hibernate.exception.SQLGrammarException: Error calling Driver#connect
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:118)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
    at com.student.bean.DBOperation.<clinit>(DBOperation.java:12)
    ... 38 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'spring'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
    at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:282)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)

DBOperation.java

    package com.student.bean;

    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;

    public class DBOperation {
    private static SessionFactory factory;
    private Session session;

    static{
    factory=new Configuration().configure("config/hibernate.cfg.xml").buildSessionFactory();
}

public Session getConnection(){
    if(session==null || !session.isOpen()){
        session=factory.openSession();
    }
    return session;
}

}

Student.java

    package com.student.bean;

    import java.io.Serializable;

    public class Student implements Serializable {
    private int rollNo;
    private String name;
    private String address;

public int getRollNo() {
    return rollNo;
}

public void setRollNo(int rollNo) {
    this.rollNo = rollNo;
}

public String getName() {
    return name;
}

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

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}
}

RegisterServlet.java

 package com.student.controller;

 import java.io.IOException;

  import javax.servlet.RequestDispatcher ;
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  import com.student.bean.Student;
   import com.student.dao.StudentDaoImpl;

   /**
       * Servlet implementation class RegisterServlet
     */
  public class RegisterServlet extends HttpServlet {
   /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String page = request.getParameter("page");
    RequestDispatcher rd = null;
    if (page != null && page.equals("update")) {
        String id = request.getParameter("roll");
        int roll = 0;
        if (id != null)
            roll = Integer.parseInt(id);
        String name = request.getParameter("name");
        String address = request.getParameter("address");

        Student student = new Student();
        student.setRollNo(roll);
        student.setName(name);
        student.setAddress(address);

        boolean flag = new StudentDaoImpl().updateStudent(student);
        if (flag == true)
            rd = request.getRequestDispatcher("update.jsp?status=sucess");
        else
            rd = request.getRequestDispatcher("update.jsp?status=fail");
    } else {
        String id = request.getParameter("roll");
        int roll = 0;
        if (id != null)
            roll = Integer.parseInt(id);
        String name = request.getParameter("name");
        String address = request.getParameter("address");

        Student student = new Student();
        student.setRollNo(roll);
        student.setName(name);
        student.setAddress(address);

        boolean flag = new StudentDaoImpl().addStudent(student);
        if (flag == true)
            rd = request.getRequestDispatcher("register.jsp?status=sucess");
        else
            rd = request.getRequestDispatcher("register.jsp?status=fail");
    }
    if (rd != null)
        rd.forward(request, response);
}

 }

StudentDao.java

 package com.student.dao;

 import com.student.bean.Student;

 public interface StudentDao {
 boolean addStudent(Student student);
 boolean updateStudent(Student student);
 Student viewStudent(int roll);
 boolean deleteStudent(int roll);
 }

StudentDaoImpl.java

    package com.student.dao;

    import org.hibernate.Query;
       import org.hibernate.Session;
     import org.hibernate.Transaction;
      import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
   import org.springframework.core.io.ClassPathResource;
   import org.springframework.core.io.Resource;

import com.student.bean.DBOperation;
  import com.student.bean.Student;

public class StudentDaoImpl implements StudentDao {
private static Resource resource;
private static BeanFactory factory;
private Session session;
private Transaction transaction;

static{
    resource=new ClassPathResource("config/spring-hibernate.xml");
    factory=new XmlBeanFactory(resource);
}

public boolean addStudent(Student student) {
    if(session==null || !session.isOpen())
        session=((DBOperation)factory.getBean("con")).getConnection();
    if(session!=null && session.isOpen()){
        transaction=session.beginTransaction();
        int id=(Integer)session.save(student);
        if(id>0){
            transaction.commit();
            session.close();
            return true;
        }
    }
    return false;
}

public boolean updateStudent(Student student) {
    if(session==null || !session.isOpen())
        session=((DBOperation)factory.getBean("con")).getConnection();
    if(session!=null && session.isOpen()){
        transaction=session.beginTransaction();
        Query query=session.createQuery("update Student set name=?,address=? where id=?");
        query.setParameter(0, student.getName());
        query.setParameter(1, student.getAddress());
        query.setParameter(2, student.getRollNo());
        int count=query.executeUpdate();
        if(count>0){
            System.out.println("student updated");
            transaction.commit();
            session.close();
            return true;
        }
    }
    return false;
}

public Student viewStudent(int roll) {
    System.out.println("finding student :"+roll);
    if(session==null || !session.isOpen())
        session=((DBOperation)factory.getBean("con")).getConnection();
    if(session!=null && session.isOpen()){
        Student student=(Student)session.get(Student.class, roll);
        if(student!=null){
            System.out.println("student found");
            return student;
        }
    }
    return null;
}

public boolean deleteStudent(int roll) {
    if(session==null || !session.isOpen())
        session=((DBOperation)factory.getBean("con")).getConnection();
    if(session!=null && session.isOpen()){
        transaction=session.beginTransaction();
        Query query=session.createQuery("delete from Student where id=?");
        query.setParameter(0, roll);
        int count=query.executeUpdate();
        if(count>0){
            System.out.println("student deleted");
            transaction.commit();
            session.close();
            return true;
        }
    }
    return false;
}

 }

的hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
 <session-factory>
    <property           name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
     <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping resource="mapping/Student.hbm.xml"/>
 </session-factory>
 </hibernate-configuration>

student.hibernate.xml

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

<bean id="std" class="com.student.bean.Student">
<property name="rollNo" value=""></property>
<property name="name" value=""></property>
<property name="address" value=""></property>
</bean>

<bean id="con" class="com.student.bean.DBOperation">
 </bean>

 </beans>

register.jsp

<html>
   <head>
<meta charset="UTF-8">
<title>Insert title here</title>

</head>
<body>

<center>
<table>
    <tr><td colspan="4"><center>Employee</center></td></tr>
    <tr><td><a href="register.jsp">Register</a></td>
        <td><a href="view.jsp">View</a></td>
        <td><a href="update.jsp">Update</a></td>
        <td><a href="delete.jsp">Delete</a></td>
    </tr>
    <tr><td colspan="4">
        <center><br>
        <%if(request.getParameter("status")!=null && request.getParameter("status").equals("sucess")){ %>
            <font color="green">Student Registered successfully</font>
        <%}else if(request.getParameter("status")!=null && request.getParameter("status").equals("fail")){ %>
            <font color="red">Student not Registered </font>
        <%} %>
    <br>
        <form action="Student.register" method="post">
            <table>
                <tr><td colspan="2"><center>Register Employee</center><br>     <hr></td></tr>
                <tr><td>Student Roll :</td><td><input type="text"     name="roll" required="required"></td></tr>
                <tr><td>Student Name :</td><td><input type="text" name="name" required="required"></td></tr>
                <tr><td>Student Address :</td><td><input type="text" name="address" required="required"></td></tr>
                <tr><td colspan="2"><center><input type="submit" value="Register"></center></td></tr>
            </table>
        </form>         
        </center>
    </td></tr>
</table>
</center>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

抱怨mysql中不存在'spring'数据库。也许您必须在运行示例之前创建它。它来自这条线:

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring</property>

在你的hibernate.cfg.xml文件中。如果您有一个具有不同名称的数据库,则可以在那里进行更改。也许该示例带有一些您打算运行的脚本,它会创建并填充数据库。