无法持久化实体(单向多对一关系)

时间:2013-07-16 19:40:04

标签: java jpa persistence eclipselink hana

我有一种情况,我有一个实体OrderedItem,它与另一个实体Order有多对一的关系。当我尝试持久保存Order实体时,收到以下错误:

> The bean encountered a non-application exception; nested exception is:
> javax.persistence.PersistenceException: Exception [EclipseLink-4002]
> (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b):
> org.eclipse.persistence.exceptions.DatabaseException Internal
> Exception: com.sap.db.jdbc.exceptions.JDBCDriverException: SAP DBTech
> JDBC: [257]: sql syntax error: incorrect syntax near "ORDER": line 1
> col 13 (at pos 13) Error Code: 257 Call: INSERT INTO ORDER (ID,
> ORDEREDAT, STATUS, TABLE, acceptor_id, waiter_id) VALUES (?, ?, ?, ?,
> ?, ?) bind => [6 parameters bound] Query:
> InsertObjectQuery([Timestamp: 2013-07-16 19:17:56.708 Table: 365
> Status: NEW Waiter: [ID: 1 EGN: 9999999999 Name: Kukata Role: [Role:
> Manager]] Acceptor: [ID: 1 EGN: 9999999999 Name: Kukata Role: [Role:
> Manager]]])

这是我的订单实体

@Entity
public class Order implements Serializable {
private static final long serialVersionUID = 1L;

public static enum Status{
    NEW,
    PROCESSED
}

@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private long id;

@NotNull
@Column(nullable = false)
private Timestamp orderedAt;

@NotNull
@Column(nullable = false)
private Integer table;

@NotNull
@ManyToOne(optional = false)
@JoinColumn(name = "waiter_id", referencedColumnName = "id")
private Employee waiter;

@NotNull
@Enumerated(EnumType.STRING)
private Status status;

@ManyToOne(optional = true)
@JoinColumn(name = "acceptor_id", referencedColumnName = "id")
private Employee acceptor;

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public Timestamp getOrderedAt() {
    return orderedAt;
}

public void setOrderedAt(Timestamp param) {
    this.orderedAt = param;
}

public Integer getTable() {
    return table;
}

public void setTable(Integer param) {
    this.table = param;
}

public Employee getWaiter() {
    return waiter;
}

public void setWaiter(Employee param) {
    this.waiter = param;
}

public Status getStatus() {
    return status;
}

public void setStatus(Status param) {
    this.status = param;
}

public Employee getAcceptor() {
    return acceptor;
}

public void setAcceptor(Employee param) {
    this.acceptor = param;
}

@Override
public String toString() {
    return new StringBuilder().append("[Timestamp: ").append(orderedAt)
            .append("\tTable: ").append(table).append("\tStatus: ")
            .append(status).append("\tWaiter: ").append(waiter)
            .append("\tAcceptor: ").append(acceptor).append("]").toString();


 }
}

这是我的orderedItem实体

@Entity
@Table(name = "OrderedItem")
public class OrderedItem implements Serializable {

    private static final long serialVersionUID = 1L;

    public OrderedItem() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private long id;

    @NotNull
    @Column(nullable = false)
    private Integer quantity;

    @NotNull
    @Column(nullable = false)
    private Double price;

    @NotNull
    @OneToOne(optional = false)
    @JoinColumn(name = "item_id", referencedColumnName = "id")
    private Item item;

    @NotNull
    @ManyToOne(optional = false)
    @JoinColumn(name = "order_id", referencedColumnName = "id")
    private Order order;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer param) {
        this.quantity = param;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double param) {
        this.price = param;
    }

    public Item getItem() {
        return item;
    }

    public void setItem(Item param) {
        this.item = param;
    }

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order param) {
        this.order = param;
    }
    @Override
    public String toString() {
        return new StringBuilder().append("[Order: ").append(order)
                .append("Item: ").append(item).append("\tQuantity: ")
                .append(quantity).append("\tPrice: ").append(price).append("]")
                .toString();
    }
}

我的员工实体

@Entity
@Table(name = "Employee")
public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;

    public Employee() {
    }

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private long id;

    @NotNull
    @Column(nullable = false)
    private String name;

    @NotNull
    @Column(nullable = false, unique = true)
    private String egn;

    @NotNull
    @Column(nullable = false)
    private byte[] pwd;

    @NotNull
    @ManyToOne(optional = false)
    @JoinColumn(name = "Role_role", referencedColumnName = "role")
    private Role role;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getEGN() {
        return egn;
    }

    public void setEGN(String param) {
        this.egn = param;
    }

    public byte[] getPwd() {
        return pwd;
    }

    public void setPwd(byte[] param) {
        this.pwd = param;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role param) {
        this.role = param;
    }

    @Override
    public String toString() {
        return new StringBuilder().append("[ID: ").append(id).append("\tEGN: ")
                .append(egn).append("\tName: ").append(name).append("\tRole: ")
                .append(role).append("]").toString();
    }
}

一切正常,直到我尝试坚持订单实体。这是一个虚拟测试servlet

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.persistence.dao.CategoryDAO;
import org.persistence.dao.EmployeeDAO;
import org.persistence.dao.ItemDAO;
import org.persistence.dao.OrderDAO;
import org.persistence.dao.OrderedItemDAO;
import org.persistence.dao.RoleDAO;

import sbms.persistence.entities.Category;
import sbms.persistence.entities.Employee;
import sbms.persistence.entities.Item;
import sbms.persistence.entities.Order;
import sbms.persistence.entities.OrderedItem;
import sbms.persistence.entities.Role;


public class Test extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @EJB
    private CategoryDAO categoryDAO;
    @EJB
    private OrderDAO orderDAO;
    @EJB
    private OrderedItemDAO orderedItemDAO;
    @EJB
    private ItemDAO itemDAO;
    @EJB
    private RoleDAO roleDAO;
    @EJB
    private EmployeeDAO employeeDAO;


    public Test() {
        super();
        // TODO Auto-generated constructor stub
    }


    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        try {
            response.getWriter().print(
                    "<p>Checking if the Role 'Manager' exists.</p>");
            Role managerRole = null;
            List<Role> roles = roleDAO.getAll(
                    "select X from Role X where X.role = ?1",
                    Role.ERoles.Manager);
            if (roles.size() == 0) {
                response.getWriter().print(
                        "<p>The role 'manager' does not exist. Adding it.</p>");
                Role role = new Role();
                role.setRole(Role.ERoles.Manager);
                roleDAO.add(role);
                managerRole = role;
            } else {
                response.getWriter().print(
                        "<p>The role 'manager' does exists.</p>");
                managerRole = roles.get(0);
            }

            response.getWriter().print(
                    "<p>Checking if there are any managers</p>");
            List<Employee> employes = employeeDAO.getAll(
                    "select X from Employee X where X.role = ?1", managerRole);
            if (employes.size() == 0) {
                response.getWriter().print(
                        "<p>There are no managers. Adding new one.</p>");
                Employee employee = new Employee();
                employee.setEGN("9999999999");
                employee.setName("Kukata");
                employee.setPwd("password".getBytes());
                employee.setRole(managerRole);
                employeeDAO.add(employee);
            }

            response.getWriter().print("<p>Checking for category 'Vodka'</p>");
            Category category = null;
            List<Category> categories = categoryDAO.getAll(
                    "select X from Category X where X.name = ?1", "Vodka");
            if (categories.size() == 0) {
                category = new Category();
                response.getWriter().print("<p>Adding category Vodka</p>");
                category.setName("Vodka");
                categoryDAO.add(category);
            }else{
                category = categories.get(0);
            }


            response.getWriter().print("<p>Checking for Russian Standard :D</p>");
            Item item = null;
            List<Item> items = itemDAO.getAll("select X from Item X where X.name = ?1", "RussianStandard");
            if(items.size() == 0){
                response.getWriter().print(
                        "<p>Adding item vodka Russian Standard</p>");
                item = new Item();
                item.setCategory(category);
                item.setPrice(35.6);
                item.setName("RussianStandard");
                itemDAO.add(item);
            }else{
                item = items.get(0);
            }


            response.getWriter().print("<p>Making an order</p>");
            // Get the employee who accepted the order (in this example -
            // Kukata)
            List<Employee> acceptor = employeeDAO.getAll(
                    "select X from Employee X where X.egn = ?1", "9999999999");
            if (acceptor.size() == 0) {
                response.getWriter().print(
                        "<p>Error -there is no such employee</p>");
                return;
            }
            Order order = new Order();
            order.setStatus(Order.Status.NEW);
            order.setOrderedAt(new Timestamp(System.currentTimeMillis()));
            order.setTable(365);
            // Kuakata accepted and processed the order!
            order.setWaiter(acceptor.get(0));
            order.setAcceptor(acceptor.get(0));
            response.getWriter().print("<p>Persisting the order</p>");
            orderDAO.add(order);

            response.getWriter().print("<p>Adding the ordered items</p>");
            OrderedItem orderedItem = new OrderedItem();
            // We set the previously created item(vodka), but we can also get it
            // from the db
            orderedItem.setItem(item);
            orderedItem.setOrder(order);
            orderedItem.setPrice(item.getPrice());
            orderedItem.setQuantity(5);
            orderedItemDAO.add(orderedItem);            

            response.getWriter().print("<p>Lets see what we have done:</p>");

        } catch (Exception e) {
            response.getWriter().print(e.getMessage());
        }
    }


    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

1 个答案:

答案 0 :(得分:0)

正如Sotirios Delimanolis在评论中所说,ORDER是hana中的保留词。将其更改为其他内容可以解决问题