Java Persistence with Hibernate: Revised Edition of Hibernate in Action

Category: Programming
Author: Christian Bauer, Gavin King
3.5
All Stack Overflow 17
This Month Stack Overflow 3

Comments

by Elie   2019-07-21

From Java Persistence with Hibernate:

  • A java.util.Map can be mapped with <map>, preserving key and value pairs. Use a java.util.HashMap to initialize a property.
  • A java.util.SortedMap can be mapped with <map> element, and the sort attribute can be set to either a comparator or natural ordering for in-memory sorting. Initialize the collection with a java.util.TreeMap instance.
by anonymous   2019-07-21

The Hibernate online documentation has some very good information on mapping your classes, in particular this section on setting up subclasses:

http://docs.jboss.org/hibernate/stable/core/manual/en/html/mapping.html#mapping-declaration-subclass

You want to pay special attention to using discriminator values and such if you are storing your sub-classed objects in a common table.

You might also consider picking up a copy of Java Persistence with Hibernate, which is considered the "Hibernate Bible" amongst my co-workers.

http://www.amazon.com/Java-Persistence-Hibernate-Christian-Bauer/dp/1932394885/ref=sr_1_1?ie=UTF8&s=books&qid=1272501916&sr=8-1

by anonymous   2019-07-21

I would seriously question this comment.

Granted, Hibernate has a wealth of features, that require some investigation to understand fully. I would suggest that whoever made this comment has not read Java Persistence with Hibernate, which is a great reference.

It's also interesting to note that Grails uses Hibernate under the covers.

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).