从hibernate

时间:2016-02-11 09:50:30

标签: java hibernate jsp

我正在尝试从hibernate中检索数据。我在数据库的Users表中插入了以下数据。

userId=2
userName=kiko
password=kareem

现在我想再次检索它们,但我不知道List<>的正确转换,因为当我尝试从users1对象检索时,现在可以通过代码找到它:

out.println(users1.getUserName());

这是我的代码

login.java(servlet)

    package Controller;

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

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

    import HibernateClasses.Users;

    /**
     * Servlet implementation class login
     */
    @WebServlet("/login")
    public class login extends HttpServlet {
        private static final long serialVersionUID = 1L;

        /**
         * @see HttpServlet#HttpServlet()
         */
        public login() {
            super();
            // TODO Auto-generated constructor stub
        }

        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
        }

        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
         *      response)
         */
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            PrintWriter out = response.getWriter();
            String name = request.getParameter("username");
            String password = request.getParameter("password");
            out.println("your name is " + name);

            // Users users = new Users();

            SessionFactory sessionfactory = new Configuration().configure()
                    .buildSessionFactory();
            Session session = sessionfactory.openSession();
            session.beginTransaction();
            Query query = session.getNamedQuery("Users.IdPass");
            query.setString(0, name);
            query.setString(1, password);
             List<Users> users1 = query.list();
            Users users = (Users) query.list();


            session.getTransaction().commit();
            session.close();

            System.out.println(users.getUserName());

        }

    }

的login.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
        <div>
            <form action="login" method="POST">
                <ul>
                    <li>User <input type="text" name="username"><br></li>
                    <li>Password <input type="password" name="password"></li>
                    <input type="submit" value="Submit" />
                </ul>
            </form>
        </div>
    </body>
    </html>

Users.java

    package HibernateClasses;

    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.NamedNativeQueries;
    import javax.persistence.NamedNativeQuery;

    @Entity
    @NamedNativeQueries({
            @NamedNativeQuery(name = "Users.byId", query = "Select * from users where userId=?", resultClass = Users.class),
            @NamedNativeQuery(name = "Users.all", query = "Select * from users ", resultClass = Users.class),
            @NamedNativeQuery(name = "Users.IdPass", query = "Select * from users where userName=? and password=? ", resultClass = Users.class) })
    public class Users {
        @Id
        private int userId;
        private String userName;
        private String password;

        public int getUserId() {
            return userId;
        }

        public void setUserId(int userId) {
            this.userId = userId;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

    }

控制台

Feb 11, 2016 12:48:19 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Archive System' did not find a matching property.
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/7.0.67
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          Dec 7 2015 13:07:11 UTC
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         7.0.67.0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Windows 8.1
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            6.3
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          amd64
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             C:\Program Files\Java\jre7
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.7.0_79-b15
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         C:\kiko\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         C:\Program Files\Apache Software Foundation\Tomcat 7.0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\kiko\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Program Files\Apache Software Foundation\Tomcat 7.0
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\kiko\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Program Files\Apache Software Foundation\Tomcat 7.0\endorsed
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Feb 11, 2016 12:48:19 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Hewlett-Packard\SimplePass\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;.
Feb 11, 2016 12:48:19 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8081"]
Feb 11, 2016 12:48:19 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Feb 11, 2016 12:48:19 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 637 ms
Feb 11, 2016 12:48:19 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Feb 11, 2016 12:48:19 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.67
Feb 11, 2016 12:48:20 PM org.apache.catalina.startup.TldConfig execute
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Feb 11, 2016 12:48:20 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8081"]
Feb 11, 2016 12:48:20 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Feb 11, 2016 12:48:20 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 920 ms
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Feb 11, 2016 12:48:28 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Controller.login] in context with path [/Archive_System] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: javax.persistence.EntityListeners
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1856)
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1705)
    at org.hibernate.cfg.annotations.reflection.JPAMetadataProvider.getDefaults(JPAMetadataProvider.java:96)
    at org.hibernate.annotations.common.reflection.java.JavaReflectionManager.getDefaults(JavaReflectionManager.java:226)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1385)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1856)
    at Controller.login.doPost(login.java:58)
    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:169)
    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)

2 个答案:

答案 0 :(得分:0)

这一行

java.lang.ClassNotFoundException: javax.persistence.EntityListeners

表示您错过了一些要包含在类路径或项目中的jar文件。

您可以使用以下Maven代码添加依赖jar文件:

<!-- for JPA, use hibernate-entitymanager -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
</dependency>

答案 1 :(得分:0)

您应该更改此代码

 @NamedQueries({
            @NamedQuery(name = "Users.byId", query = "from Users u where u.userId=?"),
            @NamedQuery(name = "Users.all", query = "from Users"),
            @NamedQuery(name = "Users.IdPass", query = "from Users u where u.userName=? and u.password=? ") })

@NamedQuery

请参阅使用@NamedQueries注释Hibernate Named Query

的示例
  

Hibernate命名查询是通过某些有意义的方式使用任何查询的方法   名称。这就像使用别名一样。 Hibernate框架提供   命名查询的概念,以便应用程序员不需要   将查询分散到所有java代码。

     

有两种方法可以在hibernate中定义命名查询:

     
      
  • by annotation
  •   
  • 通过映射文件。
  •   
     

Hibernate按注释命名查询

     

如果你想在Hibernate中使用命名查询,你需要拥有   了解@NamedQuery@NameQueries注释。

     

@NameQuery注释用于定义多个命名查询。

     

@NamedQueries({ @NamedQuery( name = "findEmployeeByName", query = "from Employee e where e.name = :name" ) }) 注释用于定义单个命名查询。

     

让我们看一下使用命名查询的示例:

list()

关于列表强制转换:from返回List<Employee>子句中使用的对象。例如,在上面的查询中,它返回不需要额外强制转换的0 0 6 6 9 ? 2010 | | | | | | | | | | | | | +- 2010 only. | | | | | +----- any day of the week. | | | | +------- 9th month (September). | | | +--------- 6th day of the month. | | +----------- 6th hour of the day. | +------------- Top of the hour (minutes = 0). +--------------- Top of the minute (seconds = 0).