hibernate中的查询语法异常

hibernate中的查询语法异常,hibernate,jersey,Hibernate,Jersey,我正在尝试使用jersey和hibernate用java构建一个web应用程序,以从数据库中检索数据。我刚开始冬眠,我面临着一个问题,我甚至无法通过阅读和尝试互联网上的不同建议来解决。如果有人能帮助我,我将不胜感激 下面是我的完整代码和错误的完整堆栈跟踪 BookResource.java import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET

我正在尝试使用jersey和hibernate用java构建一个web应用程序,以从数据库中检索数据。我刚开始冬眠,我面临着一个问题,我甚至无法通过阅读和尝试互联网上的不同建议来解决。如果有人能帮助我,我将不胜感激

下面是我的完整代码和错误的完整堆栈跟踪

BookResource.java

import java.util.List;



import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.bookstrore.model.Book;
//import com.ebook.model.User;
//import com.ebook.repository.BookRepository;
import com.bookstrore.repository.BookRepositoryStub;


@Path("books")
public class BookResource {
    //private BookRepository bookRepository=new BookRepositoryStub();

    @GET
    @Produces("application/json")
    public List<Book> getBook() {
        BookRepositoryStub book = new BookRepositoryStub();
        List books = book.getBooks();
        return books;
    }

    @DELETE
    @Path("{bookId}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Response delete(@PathParam("bookId") int bookId){
         BookRepositoryStub book = new BookRepositoryStub();
            int count = book.delete(bookId);
            if(count==0){
                return Response.status(Response.Status.BAD_REQUEST).build();
            }


        return Response.ok().build();
    }

    @PUT
    @Path("{bookId}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Response update(@PathParam("bookId") int bookId, Book bo){
        BookRepositoryStub book = new BookRepositoryStub();
        int count = book.update(bookId, bo);
        if(count==0){
            return Response.status(Response.Status.BAD_REQUEST).build();

    }
        return Response.ok().build();
    }

    @POST
    @Path("book")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Response createBook(Book bo){
        bo.setBook_title(bo.getBook_title());
        bo.setBook_author(bo.getBook_author());
        bo.setBook_description(bo.getBook_description());
        bo.setBook_price(bo.getBook_price());

        BookRepositoryStub book = new BookRepositoryStub();
        book.createBook(bo);

        return Response.ok().build();
    }

}
SessionUtil.java

package com.bookstrore.model;

//import javax.imageio.spi.ServiceRegistry;

import org.hibernate.Session;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class SessionUtil {

    private static SessionUtil instance=new SessionUtil();
    private SessionFactory sessionFactory;

    public static SessionUtil getInstance(){
            return instance;
    }

    //@SuppressWarnings("deprecation")
    private SessionUtil(){
        Configuration configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                configuration.getProperties()).build();
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        //return sessionFactory;
        //sessionFactory = configuration.buildSessionFactory();
    }

    public static Session getSession(){
        Session session =  getInstance().sessionFactory.openSession();

        return session;
    }
}
BookRepositoryStub.java

package com.bookstrore.repository;

import java.util.ArrayList;


import java.util.List;

import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.Query;

import com.bookstrore.model.Book;
import com.bookstrore.model.SessionUtil;
//import com.pluralsight.model.User;

public class BookRepositoryStub {

    public void createBook(Book book) {
         Session session = SessionUtil.getSession();        
            Transaction tx = session.beginTransaction();
            createBook(session,book);        
            tx.commit();
            session.close();

    }

    private void createBook(Session session, Book bo){
        Book book=new Book();

        book.setBook_id(bo.getBook_id());
        book.setBook_title(bo.getBook_title());
        book.setBook_author(bo.getBook_author());
        book.setBook_description(bo.getBook_description());
        book.setBook_price(bo.getBook_price());


        session.save(book);
    }

    public List<Book> getBooks(){
        Session session = SessionUtil.getSession();    
        Query query = session.createQuery("select from book");
        List<Book> books =  query.list();
        session.close();
        return books;
    }
    public int delete(int id){
        Session session = SessionUtil.getSession();
        Transaction tx = session.beginTransaction();
        String hql = "delete from book where id = :book_id";
        Query query = session.createQuery(hql);
        query.setInteger("id",id);
        int rowCount = query.executeUpdate();
        System.out.println("Rows affected: " + rowCount);
        tx.commit();
        session.close();
        return rowCount;
    }

     public int update(int id, Book bo){
         if(id <=0)  
               return 0;  
         Session session = SessionUtil.getSession();
            Transaction tx = session.beginTransaction();
            String hql = "update book set book_title = :book_title, book_author = :book_author, book_description = :book_description, book_price = :book_price,  where id = :book_id";
            Query query = session.createQuery(hql);
            query.setInteger("id",id);
            query.setString("book_title",bo.getBook_title());
            query.setString("book_author",bo.getBook_author());
            query.setString("book_description",bo.getBook_description());
            query.setInteger("book_price",bo.getBook_price());

            int rowCount = query.executeUpdate();
            System.out.println("Rows affected: " + rowCount);
            tx.commit();
            session.close();
            return rowCount;
    }



}
package com.bookstrore.repository;
导入java.util.ArrayList;
导入java.util.List;
导入org.hibernate.Transaction;
导入org.hibernate.Session;
导入org.hibernate.Query;
导入com.bookstrore.model.Book;
导入com.bookstrore.model.SessionUtil;
//导入com.pluralsight.model.User;
公共类图书存储存根{
公共书籍(书籍){
Session Session=SessionUtil.getSession();
事务tx=会话.beginTransaction();
createBook(会话、书本);
tx.commit();
session.close();
}
私有void createBook(会话,Book bo){
书=新书();
book.setBook_id(bo.getBook_id());
book.setBook_title(bo.getBook_title());
book.setBook_author(bo.getBook_author());
book.setBook_description(bo.getBook_description());
book.setBook_price(bo.getBook_price());
保存(书);
}
公共列表getBooks(){
Session Session=SessionUtil.getSession();
Query=session.createQuery(“从书本中选择”);
List books=query.List();
session.close();
还书;
}
公共整数删除(整数id){
Session Session=SessionUtil.getSession();
事务tx=会话.beginTransaction();
String hql=“从书中删除,其中id=:book_id”;
Query=session.createQuery(hql);
query.setInteger(“id”,id);
int rowCount=query.executeUpdate();
System.out.println(“受影响的行:“+rowCount”);
tx.commit();
session.close();
返回行计数;
}
公共int更新(int id,Book bo){
如果(id)

而不是下面的
getBooks()

使用


参考:

而不是下面的
getBooks()

使用

Ref:

您在查询中使用了“book”而不是“book”(注意B)。“book”指的是用@Entity和@Table注释的book类

所以,您应该是这样的

提示:不要在SELECT中使用*。因为HQL

您可以使用createSQLQuery()方法执行本机查询。

您在查询中使用了“book”而不是“book”(注意B)。“book”是指用@Entity和@Table注释的book类

所以,您应该是这样的

提示:不要在SELECT中使用*。因为HQL


您可以使用createSQLQuery()方法执行本机查询。

我更改了它,它告诉我book不是按book映射的。因此,根据互联网上的不同建议,我将其更改为“from book”,至于引用Book类,在这之后,我遇到了以下错误:org.hibernate.exception.sqlgrammareexception:无法提取结果如果您创建了Book.hbm.xml,然后将其添加到hibernate.cfg.xml。关于结果集,它是SQL,您在某处混合了SQL和HQL。尝试一个教程,它可能会对您有所帮助。我还没有像以前那样创建Book.hbm.xml我在用MySQL@Lilly你能在session.createQqery中尝试使用
select*from book
并告诉我它是否有效吗?@AmitK我尝试了这个,得到了:HTTP Status 500-org.hibernate.hql.internal.ast.QuerySyntaxException:意外标记:*靠近第1行第8列[select*from book]我把它改了,它告诉我书不是按书映射的。所以,根据互联网上的不同建议,我把它改为“从书”,至于引用Book类,在这之后,我遇到了以下错误:org.hibernate.exception.sqlgrammareexception:无法提取结果如果您创建了Book.hbm.xml,然后将其添加到hibernate.cfg.xml。关于结果集,它是SQL,您在某处混合了SQL和HQL。尝试一个教程,它可能会对您有所帮助。我还没有像以前那样创建Book.hbm.xml我在用MySQL@Lilly你能在session.createQqery中尝试使用
select*from book
并告诉我它是否有效吗?@AmitK我尝试了这个,得到了:HTTP Status 500-org.hibernate.hql.internal.ast.QuerySyntaxException:意外标记:*靠近第1行第8列[select*from book]
package com.bookstrore.repository;

import java.util.ArrayList;


import java.util.List;

import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.Query;

import com.bookstrore.model.Book;
import com.bookstrore.model.SessionUtil;
//import com.pluralsight.model.User;

public class BookRepositoryStub {

    public void createBook(Book book) {
         Session session = SessionUtil.getSession();        
            Transaction tx = session.beginTransaction();
            createBook(session,book);        
            tx.commit();
            session.close();

    }

    private void createBook(Session session, Book bo){
        Book book=new Book();

        book.setBook_id(bo.getBook_id());
        book.setBook_title(bo.getBook_title());
        book.setBook_author(bo.getBook_author());
        book.setBook_description(bo.getBook_description());
        book.setBook_price(bo.getBook_price());


        session.save(book);
    }

    public List<Book> getBooks(){
        Session session = SessionUtil.getSession();    
        Query query = session.createQuery("select from book");
        List<Book> books =  query.list();
        session.close();
        return books;
    }
    public int delete(int id){
        Session session = SessionUtil.getSession();
        Transaction tx = session.beginTransaction();
        String hql = "delete from book where id = :book_id";
        Query query = session.createQuery(hql);
        query.setInteger("id",id);
        int rowCount = query.executeUpdate();
        System.out.println("Rows affected: " + rowCount);
        tx.commit();
        session.close();
        return rowCount;
    }

     public int update(int id, Book bo){
         if(id <=0)  
               return 0;  
         Session session = SessionUtil.getSession();
            Transaction tx = session.beginTransaction();
            String hql = "update book set book_title = :book_title, book_author = :book_author, book_description = :book_description, book_price = :book_price,  where id = :book_id";
            Query query = session.createQuery(hql);
            query.setInteger("id",id);
            query.setString("book_title",bo.getBook_title());
            query.setString("book_author",bo.getBook_author());
            query.setString("book_description",bo.getBook_description());
            query.setInteger("book_price",bo.getBook_price());

            int rowCount = query.executeUpdate();
            System.out.println("Rows affected: " + rowCount);
            tx.commit();
            session.close();
            return rowCount;
    }



}
<?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 name="hibernateSessionFactory">
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.password">behari</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ebooks</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.format_sql">true</property>
<!--   <property name="hibernate.hbm2ddl.auto">create</property> -->
  <mapping class="com.bookstrore.model.Book"/>
 </session-factory>
</hibernate-configuration>
 <pre>javax.servlet.ServletException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: from near line 1, column 8 [select from book]
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:487)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
        </p>
        <p>
            <b>root cause</b>
            <pre>org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: from near line 1, column 8 [select from book]
    org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:91)
    org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:109)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:304)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:203)
    org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    org.hibernate.engine.query.spi.HQLQueryPlan.&lt;init&gt;(HQLQueryPlan.java:131)
    org.hibernate.engine.query.spi.HQLQueryPlan.&lt;init&gt;(HQLQueryPlan.java:93)
    org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
    org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1836)
    com.bookstrore.repository.BookRepositoryStub.getBooks(BookRepositoryStub.java:42)
    com.bookstrore.BookResource.getBook(BookResource.java:33)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    java.lang.reflect.Method.invoke(Unknown Source)
    org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
    org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
    org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
    org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
    org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
    org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
    org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
    org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:471)
    org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:425)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:383)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:336)
    org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:223)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
   Query query = session.createQuery("select from book");
Query query = session.createQuery("from book"); 
Query query = session.createQuery("FROM Book"); // note the B
Query query = session.createQuery("SELECT b FROM Book b"); //more declarative