membersound
membersound

Reputation: 86727

How to store an ArrayList ordered with hibernate?

The elements in a list are ordered by insertion:

List<Object> list = new ArrayList<>();
list.add(obj);

Now I want to store the list in a postgres table with hibernate, and want to preserve the order of insertion. Is that possible that hibernate fetches the collection and it has the same order than before insertion?

Upvotes: 2

Views: 6791

Answers (3)

Marek Podyma
Marek Podyma

Reputation: 1083

Take look at @OrderColumn or this great article. This will do the job - it will keep order in context of given parent (List collection).

Upvotes: 0

membersound
membersound

Reputation: 86727

Finally I got the following solution:

@OneToMany(mappedBy...)
@OrderBy("id")
private Set<MyEntity>list = new  LinkedHashSet<>();

@Entity
class MyEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
}

My requirement is to just preserve the order of insertion, which is given by using a LinkedHashSet. As the database id is autogenerated and always incremented, I can just order the set by the generated ID and get a list ordered by original insertion order on select.

Upvotes: 2

bedrin
bedrin

Reputation: 4586

You will have to persist the order in the database - for example add an order property mapped to ORDER column

when getting the entities from JPA you will be able to use the @OrderBy annotation for sorting

@Entity
@Table(name = "VEHICLE")
public class Vehicle {

    // other fields here

    @OneToMany(mappedBy = "vehicle")
    @OrderBy("vehicle.order ASC")
    Set<VehicleImage> vehicleImages;

    public void addImage(VehicleImage image) {
        if (null == vehicleImages) vehicleImages = new HashSet<>();
        image.setSize(vehicleImages.size() + 1);
        image.setVehicle(this);
        vehicleImages.add(this);
    }

}

@Entity
@Table(name = "VEHICLE_IMAGE")
public class VehicleImage{

    // other fields here
    @Column(name = "ORDER")
    private int order;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumn(name="VEHICLE_ID", referencedColumnName = "ID")
    Vehicle vehicle;

}

Upvotes: 4

Related Questions