What is the difference between bag and list in hibernate




















For collections of a basic or embeddable type use ElementCollection. In the simplest case a collection mapping looks like this:.

In this unidirectional one to many scenario you can also use a join table as seen in Example 7. Without describing any physical mapping no JoinColumn or JoinTable , a unidirectional one to many with join table is used. A unique constraint is added to the foreign key referencing the other side table to reflect the one to many. Lets have a look now how collections are mapped using Hibernate mapping files. In this case the first step is to chose the right mapping element.

It depends on the type of interface. In Example 7. This association requires the existence of a foreign key column and possibly an index column to the Part table. This mapping loses certain semantics of normal Java collections:. An instance of the contained entity class cannot belong to more than one instance of the collection. An instance of the contained entity class cannot appear at more than one value of the collection index. Nor is it necessary to specify the table name anywhere.

See Section 7. It is not used for one-to-many associations. It can also be used to enable "extra-lazy" fetching where most operations do not initialize the collection. This is suitable for large collections. This is useful if the collection needs to contain only a subset of the available data. For one-to-many associations you may want to disable this setting. This allows for minor performance optimization in some cases. After exploring the basic mapping of collections in the preceding paragraphs we will now focus details like physical mapping considerations, indexed collections and collections of value types.

On the database level collection instances are distinguished by the foreign key of the entity that owns the collection. This foreign key is referred to as the collection key column , or columns, of the collection table. There can be a nullability constraint on the foreign key column.

For most collections, this is implied. For unidirectional one-to-many associations, the foreign key column is nullable by default, so you may need to specify. In XML this can be expressed via:.

See Section 5. In the following paragraphs we have a closer at the indexed collections List and Map how the their index can be mapped in Hibernate. To order lists in memory, add javax.

OrderBy to your property. This annotation takes as parameter a list of comma separated properties of the target entity and orders the collection accordingly eg firstname asc, age desc , if the string is empty, the collection will be ordered by the primary key of the target entity. To store the index value in a dedicated column, use the javax. OrderColumn annotation on your property. This annotations describes the column name and attributes of the column keeping the index value.

This column is hosted on the table containing the association foreign key. Example 7. Explicit index column using OrderColumn. We recommend you to convert the legacy org. IndexColumn usages to OrderColumn unless you are making use of the base property. The base property lets you define the index value of the first element aka as base index.

The usual value is 0 or 1. The default is 0 like in Java. The mapped column contains sequential integers that are numbered from zero by default. A bag does not retain its order when it is retrieved from the database, but it can be optionally sorted or ordered.

The question with Map s is where the key value is stored. There are everal options. Question 88 : What is a lazy initialization in Hibernate? Answer: Lazy initialization, also known as lazy fetching, is the opposite of eager loading. It means when a record is loaded for a database; the child rows are not loaded. Lazy initialization or lazy fetching of an object means that its creation is deferred till it is used first.

Answer: Optimistic locking is used to check whether the record was updated by someone else prior to committing a transaction. Pessimistic locking is used to ensure no one else can modify or access the record. Pessimistic locking: In pessimistic locking, the record gets locked on the update so that nobody else can access that record for updating. Thus, it becomes a read-only record until the lock is released again. Optimistic locking: An optimistic locking allows multiple users to open the same record for updating.

The record gets locked when updating a record only. It is the most preferred way of locking for a web application. Previous 5. Hibernate Interview Question. Ready to learn more? Contact us today. However, the java. Collection interface has bag semantics, so you only need a matching implementation. Hibernate has a built-in PersistentBag that can deal with lists; however, consistent with the contract of a bag, it ignores the position of elements in the ArrayList.

In other words, you get a persistent Collection. Map it like the previous option, but expose a different collection interface in the domain model class. We recommend the first option. Change the type of images in the Item class from Set to Collection, and initialize it with an ArrayList: Note that the setter method accepts a Collection, which can be anything in the JDK collection interface hierarchy.

However, Hibernate is smart enough to replace this when persisting the collection. It also relies on an ArrayList internally, like you did in the declaration of the field. Hibernate manages it internally. A more likely scenario is one in which you wish to preserve the order in which images are attached to the Item.

There are a number of good ways to do this; one way is to use a real list, instead of a bag. The index column defines the position of the element in the collection. Thus, Hibernate is able to preserve the ordering of the collection elements.

The index of the persistent list starts at zero. Alternatively, you could map a Java array instead of a list. However, for reasons explained earlier, Hibernate applications rarely use arrays.

Now, suppose that the images for an item have user-supplied names in addition to the filename. One way to model this in Java is a map, with names as keys and filenames as values of the map.

Again, duplicate elements are allowed; see figure 6. This map is unordered. What if you want to always sort your map by the name of the image? Sorted and ordered collections In a startling abuse of the English language, the words sorted and ordered mean different things when it comes to Hibernate persistent collections. A sorted collection is sorted in memory using a Java comparator.

An ordered collection is ordered at the database level using an SQL query with an order by clause. First, you need to change the initialization of the Java property to a java. TreeMap and switch to the java. If you need some other sort algorithm for example, reverse alphabetical order , you may specify the name of a class that implements java.

Comparator in the sort attribute. For example: A java. SortedSet with a java. TreeSet implementation is mapped like this: Bags may not be sorted there is no TreeBag, unfortunately , nor may lists; the order of list elements is defined by the list index. You can even include an SQL function call in the order-by attribute: You can order by any column of the collection table.

Internally, Hibernate uses a LinkedHashMap, a variation of a map that preserves the insertion order of key elements.

In other words, the order that Hibernate uses to add the elements to the collection, during loading of the collection, is the iteration order you see in your application. The same can be done with a set: Hibernate internally uses a LinkedHashSet. Internally, Hibernate uses an ArrayList to implement a bag that preserves insertion-iteration order: The linked collections Hibernate uses internally for sets and maps are available only in JDK 1.

This is the perfect use case for a collection of components. Collections of components You could map Image as an entity class and create a one-to-many relationship from Item to Image.

As a value type, the Image class defines the properties name, filename, sizeX, and sizeY. It has a single association with its owner, the Item entity class, as shown in figure 6. As you can see from the composition association style the black diamond , Image is a component of Item, and Item is the entity that is responsible for the lifecycle of Image instances.

The multiplicity of the association further declares this association as many-valued—that is, many or zero Image instances for the same Item instance. You must implement equals and hashCode and compare the name, filename, sizeX, and sizeY properties. Hibernate relies on this equality routine to check instances for modifications. The Item class may have a Set of images, with no duplicates allowed.

Mapping the collection Collections of components are mapped similarly to collections of JDK value type. An ordered set of images internally, a LinkedHashSet can be mapped like this: The tables with example data are shown in figure 6. This is probably a disadvantage of this particular mapping. You can navigate to the images by accessing the collection through an Item instance and iterating: anItem. This is the only way you can get these image objects; no other entity holds a reference to them value type again.

However, it may be convenient to access a back pointer like anIm-age. This is an important issue: You can load Image instances by querying for them. Finally, declaring all properties as not-null is something you may not want. You need a different primary key for the IMAGE collection table, if any of the property columns are nullable. They may be nullable, as can be seen in figure 6.

The tables are identical. The choice is mainly a matter of taste. Value-typed instances can be created and associated with the persistent Item by adding a new element to the collection. But in bag with Id's, the element which has been removed only gets removed, rest of the elements are not impacted. While in list with order, the data structure maintains an indexing order. So, if you remove one of the elements. Hence, this type of list is used to maintain the order in which the elements are inserted into the list.

Also, note that although ordering is persisted in the seperate column of table. It doesn't appears on the object state, when you fetch. Hence, it is just used for internal operations. Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Asked 7 years, 7 months ago.



0コメント

  • 1000 / 1000