Stefan
Stefan

Reputation: 1041

Hibernate autoincrement ManyToOne weak entity

I was wondering whats the best way to autoincrement my order rows in hibernate? Starting at 1 and going up isn't a problem. But I want my order row id to reset when added to a new order.

Pretty much like this:

OrderID    OrderRowID
1          1
1          2
2          1
2          2
2          3
3          1
3          2

Order:

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

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

OrderRow:

@Entity
@Table(name = "order_row")
public class OrderRow {
    @Id
    @Column(name = "id")
    private Integer id;

    @ManyToOne
    @JoinColumn(name="album_id")
    private Order order;

The weak entity mapping works fine but I have to set order id's manually at the moment.

Upvotes: 0

Views: 75

Answers (1)

Stefan
Stefan

Reputation: 1041

I solved it in a bad way in my opinion: I created a get next id function in my OrderRow DAO which just does another select request like this:

public Integer getNextId(Order o) {
    String q = "FROM OrderRow WHERE order_id = :orderId";
    Query query = session.createQuery(q);
    query.setParameter("orderId", o.getId());

    List<OrderRows> orderRows =  query.list();

    int id = 1;

    if (orderRows.size() > 0) {
        id = orderRows.get(orderRows.size()-1).getId();
        id++;
    }

    return id;
}

I hope I can help atleast someone with this solution.

Upvotes: 0

Related Questions