您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在附近使用正确的语法

时间:2017-03-10 12:51:51

标签: spring hibernate

当我尝试登录时遇到此问题:

WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 1064, SQLState: 42000
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order orders0_ where orders0_.user_id=10' at line 1
ERROR: org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - An internal error occurred while trying to authenticate the user.
org.springframework.security.authentication.InternalAuthenticationServiceException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order orders0_ where orders0_.user_id=10' at line 1

这里是实体用户和订单:

@Entity
@Table(name = "user")
public class User {

    private int id;
    private String firstname;
    private String lastname;
    private String email;
    private String telephone;
    private String sex;
    private String password;
    private String confirmPassword;
    private String login;

    private Set<Role> roles = new HashSet<Role>(0);
    private Set<Product> products = new HashSet<Product>(0);
    private Set<Order> orders = new HashSet<Order>(0);

    public User(){}

    ...

    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    public Set<Order> getOrders() {
        return orders;
    }

    public void setOrders(Set<Order> orders) {
        if(orders!=null){
            this.orders = orders;
        }
    }
}

@Entity
@Table(name="order")
public class Order {

    private int id;
    private OrderStatus status;
    private DeliveryType deliveryType;
    private Date date;
    private PaymentType paymentType;
    private String receiver;
    private String phone;
    private String email;
    private BigDecimal deliveryPrice;
    private String address;
    private String cardNumber;
    private String cardTermOf;
    private int cardThreeNumbers;

    public Order(){}

    private User user;  

    private Set<ProductsInOrder> productsInOrders = new HashSet<ProductsInOrder>();

    ...

    @ManyToOne
    @JoinColumn(name = "user_id")
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}

当我在方法getOrderds()上的用户实体中FetchType.EAGER上更改FetchType.LAZY时,我可以成功登录,但当我尝试获取订单时,我收到错误:

  

未能懒惰地初始化角色集合:“ua.sombra.webstore.domain.User.orders,无法初始化代理 - 无会话”

我无法解决这个问题。我需要做什么?

2 个答案:

答案 0 :(得分:2)

您的问题是order是SQL中的保留字,您不能将其用作表的名称。将其重命名为orders或smth ..

答案 1 :(得分:1)

正如@veljkost所提到的,order是一个保留字,因此你必须重命名它。

但是,我有一个建议。不要使用急切提取,因为从长远来看会导致性能问题。

了解延迟加载的工作原理并正确使用它。

查看本文以了解您获得该例外的原因:http://blog.arnoldgalovics.com/2017/02/27/lazyinitializationexception-demystified/