Java Persistence with Hibernate: Revised Edition of Hibernate in Action

Author: Christian Bauer, Gavin King
3.5
All Stack Overflow 17

Comments

by anonymous   2017-08-20

After a look through the hibernate documentation and This Book i was able to find a solution to my problem. i cannot use an interface for the moment with JPA annotations. so i used an abstract class with mappings that supported inheritance. in this example i use a single table to store all the values. but i wil look in to seperating them.

@Entity
@Table(name ="HIERARCHY")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(
    name = "HIERARCHY_TYPE", discriminatorType = DiscriminatorType.STRING)      
public abstract class  Hierarchy implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "hierarchy_id", updatable = false, nullable = false)
private int hId;



@Entity
@DiscriminatorValue("F")
public class Folder extends Hierarchy  {

@OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinTable(name = "FOLDER_JOIN_FILELOCATION", joinColumns = { 
        @JoinColumn(name = "folder_id") }, inverseJoinColumns = { 
        @JoinColumn(name = "file_information_id") })
private List<Hierarchy> children = new ArrayList<Hierarchy>() ;
@Column(name = "folder_name")
private String folderName;
//@Column(name = "tree_item")
//private TreeItem item;
@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
   @JoinTable(name="FOLDER_JOIN_FOLDER",
        joinColumns = @JoinColumn(name="parent_folder_id"),
        inverseJoinColumns = @JoinColumn(name="folder_ID")
    ) 
private Hierarchy parent;




@Entity
@DiscriminatorValue("FI")
public class FileInformation extends Hierarchy  {


@Column (name = "location")
private String location;
//@Column(name = "tree_item")
//private TreeItem item;
@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
   @JoinTable(name="FILEINFORMATION_JOIN_FOLDER",
        joinColumns = @JoinColumn(name="filelocation_id"),
        inverseJoinColumns = @JoinColumn(name="folder_ID")
    )  
private Hierarchy parent;
by anonymous   2017-08-20

Page 537 of Java Persistence with Hibernate gives a solution using ScrollableResults, but alas it's only for Hibernate.

So it seems that using setFirstResult/setMaxResults and manual iteration really is necessary. Here's my solution using JPA:

private List<Model> getAllModelsIterable(int offset, int max)
{
    return entityManager.createQuery("from Model m", Model.class).setFirstResult(offset).setMaxResults(max).getResultList();
}

then, use it like this:

private void iterateAll()
{
    int offset = 0;

    List<Model> models;
    while ((models = Model.getAllModelsIterable(offset, 100)).size() > 0)
    {
        entityManager.getTransaction().begin();
        for (Model model : models)
        {
            log.info("do something with model: " + model.getId());
        }

        entityManager.flush();
        entityManager.clear();
        em.getTransaction().commit();
        offset += models.size();
    }
}
by anonymous   2017-08-20

Hibernate can help you solve all the three problems you listed.

(1) You need to annotate your entity classes so Hibernate is able to map between classes/objects to tables/rows. Hibernate uses a convention over configuration approach so it is possible to use just a few annotations and have a complete o/r mapping ready for use. You could use the hibernate.hbm2ddl.auto configuration option to instruct Hibernate to automatically validate/export and schema DDL when the session factory is first created.

(2) / (3) Hibernate has enough information about classes, database schema and mappings to allow it generate SQL statements for simple CRUD operations with minimal effort. You can fine tune how Hibernate loads and persists a tree of objects. Association mapping annotations have the fetch and cascade options that let you specify how associated objects are fetched (lazy / eager) and how operations are propagated through the object tree. Please refer to the Hibernate documentations for the details about these options.

If you are new to Hibernate, I recommend the good Hibernate documentation as reference and the book Java Persistence with Hibernate for the deeper understanding about the framework (it has very good sections about fetching and cascading).

In a typical scenario, Hibernate requires just a bit of configuration (one hibernate.cfg.xml file). You can define the mappings using XML files (no good) or annotations (the "default" option for new projects).