Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting all but one column with hibernate on a table with foreign

Tags:

java

hibernate

I have working .jsp webapp that is using Hibernate to manage database stuff. As the webapp have grown in time I now face the the memory problem issues on the server. So I need to rewrite it a little to consume less memory.

My code is as follows:

@Table(name="items")
public class Items implements Serializable {

  @Id
  @GeneratedValue
  @Column(name="ID")
  private long id;

  @Column(name="Name", nullable=false)
  private String name;

  @Column(name="Image", nullable=true, length=1048576)
  private byte[] image;

  @Column(name="Text", nullable=true, columnDefinition="TEXT")
  private String text;

  @Column(name="AvailablePieces", nullable=true)
  private int storedAmount;

  @Column(name="Price", nullable=true)
  private int price;

  @ManyToOne
  @JoinColumn(name="colorId")
  private ItemColors color;

  @OneToMany(mappedBy = "key.item")
  @Cascade(CascadeType.ALL)
  Set<Orders_Items> orderItems = new HashSet<Orders_Items>();

....

}

And SELECT is

@NamedQuery(itemsByName",
    query = "* FROM Items i WHERE (i.name LIKE '%' || :iname || '%')"
),

The thing is that a common usage is fetching ~500 records at once, while only about 10-15 needs to display its image.

Is there a way to tell Hibernate to select all columns except for Image in one SELECT, and then later on when items that needs its image are calculated to perform another SELECT to retrieve images (something like "SELECT i.image FROM Items i WHERE i.id = :id")?

In other words: What is the proper syntaxt for selecting specific columns, including @ManyToOne mapped columns - it throws ClassCastException for something like "SELECT i.color FROM..."?

like image 761
ondarsky Avatar asked Oct 21 '25 14:10

ondarsky


1 Answers

Use the projection feature:

How to return an entity with chosen columns using Criteria

The other is to do lazy-fetching:

http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/performance.html#performance-fetching-lazyproperties

like image 168
dispake Avatar answered Oct 23 '25 04:10

dispake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!