Posts

Showing posts with the label hibernate

Hibernate JPA @WhereJoinTable Example

@WhereJoinTable The @WhereJoinTable annotation is used to specify a custom SQL WHERE clause used when fetching a join collection table. WhereJoinTable Where clause to add to the collection join table. The clause is written in SQL. Just as with Where, a common use case is for implementing soft-deletes. @WhereJoinTable Just like @Where annotation, @WhereJoinTable is used to filter out collections using a joined table (e.g. @ManyToMany association). Example : @WhereJoinTable mapping example @Entity(name = "Book") public static class Book { @Id private Long id; private String title; private String author; @ManyToMany @JoinTable( name = "Book_Reader", joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name = "reader_id") ) @WhereJoinTable( clause = "created_on > DATEADD( 'DAY', -7, CURRENT_TIMESTAMP() )") private List<Reader> currentWeekReaders = new Arra...

Hibernate JPA @Where Example

@Where The @Where annotation is used to specify a custom SQL WHERE clause used when fetching an entity or a collection. Where clause to add to the element Entity or target entity of a collection. The clause is written in SQL. A common use case here is for soft-deletes. @Where mapping usage public enum AccountType { DEBIT, CREDIT } @Entity(name = "Client") public static class Client { @Id private Long id; private String name; @Where( clause = "account_type = 'DEBIT'") @OneToMany(mappedBy = "client") private List<Account> debitAccounts = new ArrayList<>( ); @Where( clause = "account_type = 'CREDIT'") @OneToMany(mappedBy = "client") private List<Account> creditAccounts = new ArrayList<>( ); //Getters and setters omitted for brevity } @Entity(name = "Account") @Where( clause = "active = true" ) public static class Account { @Id p...

Hibernate JPA @ValueGenerationType Example

@ValueGenerationType The @ValueGenerationType annotation is used to specify that the current annotation type should be used as a generator annotation type. ValueGenerationType marks an annotation type as a generator annotation type. Adding a generator annotation to an entity property causes the value of the property to be generated upon insert or update of the owning entity. Not more than one generator annotation may be placed on a given property. Each generator annotation type is associated with a AnnotationValueGeneration which implements the strategy for generating the value. Generator annotation types may define arbitrary custom attributes, e.g. allowing the client to configure the generation timing (if applicable) or other settings taking an effect on the value generation. The corresponding implementation can retrieve these settings from the annotation instance passed to AnnotationValueGeneration.initialize(java.lang.annotation.Annotation, Class). Custom generator annota...

Hibernate JPA @UpdateTimestamp Example

@UpdateTimestamp The @UpdateTimestamp annotation is used to specify that the currently annotated timestamp attribute should be updated with the current JVM timestamp whenever the owning entity gets modified. java.util.Date java.util.Calendar java.sql.Date java.sql.Time java.sql.Timestamp UpdateTimestamp marks a property as the update timestamp of the containing entity. The property value will be set to the current VM date whenever the owning entity is updated. Supported property types: Date Calendar Date Time Timestamp Instant LocalDate LocalDateTime LocalTime MonthDay OffsetDateTime OffsetTime Year YearMonth ZonedDateTime @UpdateTimestamp annotation The @UpdateTimestamp annotation instructs Hibernate to set the annotated entity attribute with the current timestamp value of the JVM when the entity is being persisted. The supported property types are: java.util.Date java.util.Calendar java.sql.Date java.sql.Time java.sql.Timestamp ...

Hibernate JPA @TypeDef Example

@TypeDef The @TypeDef annotation is used to specify a @Type definition which can later be reused for multiple basic attribute mappings. TypeDef is a type definition. Much like Type, but here we can centralize the definition under a name and refer to that name elsewhere. The plural form is TypeDefs. @TypeDef to register a custom Type @Entity(name = "Product") @TypeDef( name = "bitset", defaultForType = BitSet.class, typeClass = BitSetType.class ) public static class Product { @Id private Integer id; private BitSet bitSet; //Getters and setters are omitted for brevity } @TypeDefs The @TypeDefs annotation is used to group multiple @TypeDef annotations.

Hibernate JPA @Type Example

@Type The @Type annotation is used to specify the Hibernate @Type used by the currently annotated basic attribute. Custom BasicType mapping @Entity(name = "Product") public static class Product { @Id private Integer id; @Type( type = "bitset" ) private BitSet bitSet; public Integer getId() { return id; } //Getters and setters are omitted for brevity }

Hibernate JPA @Tuplizer Example

@Tuplizer The @Tuplizer annotation is used to specify a custom tuplizer for the currently annotated entity or embeddable. For entities, the tupelizer must implement the EntityTuplizer interface. For embeddables, the tupelizer must implement the ComponentTuplizer interface. Dynamic entity proxies using the @Tuplizer annotation It is possible to map your entities as dynamic proxies using the @Tuplizer annotation. In the following entity mapping, both the embeddable and the entity are mapped as interfaces, not POJOs. Example : Dynamic entity proxy mapping @Entity @Tuplizer(impl = DynamicEntityTuplizer.class) public interface Cuisine {     @Id     @GeneratedValue     Long getId();     void setId(Long id);     String getName();     void setName(String name);     @Tuplizer(impl = DynamicEmbeddableTuplizer.class)     Country getCountry();     void setCountry(Country country);...

Hibernate JPA @Target Example

@Target The @Target annotation is used to specify an explicit target implementation when the currently annotated association is using an interface type. Target define an explicit target, avoiding reflection and generics resolving. @Target mapping The @Target annotation is used to specify the implementation class of a given association that is mapped via an interface. The @ManyToOne, @OneToOne, @OneToMany, and @ManyToMany feature a targetEntity attribute to specify the actual class of the entity association when an interface is used for the mapping. The @ElementCollection association has a targetClass attribute for the same purpose. However, for simple embeddable types, there is no such construct and so you need to use the Hibernate-specific @Target annotation instead. Example :@Target mapping usage public interface Coordinates { double x(); double y(); } @Embeddable public static class GPS implements Coordinates { private double latitude; private double l...

Hibernate JPA @Table Example

@Table The @Table annotation is used to specify additional information to a JPA @Table annotation, like custom INSERT, UPDATE or DELETE statements or a specific FetchMode. Table is Complementary information to a table either primary or secondary. Example: @Entity(name = "Person") @Table(name = "person") @SQLInsert(     sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) " ) @SQLDelete(     sql = "UPDATE person SET valid = false WHERE id = ? " ) @SecondaryTable(name = "person_details",     pkJoinColumns = @PrimaryKeyJoinColumn(name = "person_id")) @org.hibernate.annotations.Table(     appliesTo = "person_details",     sqlInsert = @SQLInsert(         sql = "INSERT INTO person_details (image, person_id, valid) VALUES (?, ?, true) ",         check = ResultCheckStyle.COUNT     ),     sqlDelete = @SQLDelete(         sql = "UPDA...

Hibernate JPA @Synchronize Example

@Synchronize The @Synchronize annotation is usually used in conjunction with the @Subselect annotation to specify the list of database tables used by the @Subselect SQL query. With this information in place, Hibernate will properly trigger an entity flush whenever a query targeting the @Subselect entity is to be executed while the Persistence Context has scheduled some insert/update/delete actions against the database tables used by the @Subselect SQL query. Therefore, the @Synchronize annotation prevents the derived entity from returning stale data when executing entity queries against the @Subselect entity. Synchronize Ensures that auto-flush happens correctly and that queries against the derived entity do not return stale data. Mostly used with Subselect. @Entity(name = "Client") @Table(name = "client") public static class Client { @Id private Long id; @Column(name = "first_name") private String firstName; @Column(name = "...

Hibernate JPA @Subselect Example

@Subselect The @Subselect annotation is used to specify an immutable and read-only entity using a custom SQL SELECT statement. Subselect Map an immutable and read-only entity to a given SQL select expression. Mapping the entity to a SQL query You can map an entity to a SQL query using the @Subselect annotation. Example : @Subselect entity mapping @Entity(name = "Client") @Table(name = "client") public static class Client { @Id private Long id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; //Getters and setters omitted for brevity } @Entity(name = "Account") @Table(name = "account") public static class Account { @Id private Long id; @ManyToOne private Client client; private String description; //Getters and setters omitted for brevity } @Entity(name = "AccountTransaction") @Table(name = "accoun...

Hibernate JPA @SQLUpdate Example

@SQLUpdate The @SQLUpdate annotation is used to specify a custom SQL UPDATE statement for the currently annotated entity or collection. Custom CRUD @Entity(name = "Person") @SQLInsert( sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) ", check = ResultCheckStyle.COUNT ) @SQLUpdate( sql = "UPDATE person SET name = ? where id = ? " ) @SQLDelete( sql = "UPDATE person SET valid = false WHERE id = ? " ) @Loader(namedQuery = "find_valid_person") @NamedNativeQueries({ @NamedNativeQuery( name = "find_valid_person", query = "SELECT id, name " + "FROM person " + "WHERE id = ? and valid = true", resultClass = Person.class ) }) public static class Person { @Id @GeneratedValue private Long id; private String name; @ElementCollection @SQLInsert( sql = "INSERT INTO person_phones (person_id, phones, valid) VALUES (?, ?, true) ...

Hibernate JPA @SQLInsert Eample

@SQLInsert The @SQLInsert annotation is used to specify a custom SQL INSERT statement for the currently annotated entity or collection. Custom CRUD @Entity(name = "Person") @SQLInsert( sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) ", check = ResultCheckStyle.COUNT ) @SQLUpdate( sql = "UPDATE person SET name = ? where id = ? " ) @SQLDelete( sql = "UPDATE person SET valid = false WHERE id = ? " ) @Loader(namedQuery = "find_valid_person") @NamedNativeQueries({ @NamedNativeQuery( name = "find_valid_person", query = "SELECT id, name " + "FROM person " + "WHERE id = ? and valid = true", resultClass = Person.class ) }) public static class Person { @Id @GeneratedValue private Long id; private String name; @ElementCollection @SQLInsert( sql = "INSERT INTO person_phones (person_id, phones, valid) VALUES (?, ?, true) ...

Hibernate JPA @SqlFragmentAlias Example

@SqlFragmentAlias The @SqlFragmentAlias annotation is used to specify an alias for a Hibernate @Filter. The alias (e.g. myAlias) can then be used in the @Filter condition clause using the {alias} (e.g. {myAlias}) placeholder. @Filter with @SqlFragmentAlias When using the @Filter annotation and working with entities that are mapped onto multiple database tables, you will need to use the @SqlFragmentAlias annotation if the @Filter defines a condition that uses predicates across multiple tables. Example :@SqlFragmentAlias mapping usage @Entity(name = "Account") @Table(name = "account") @SecondaryTable( name = "account_details" ) @SQLDelete( sql = "UPDATE account_details SET deleted = true WHERE id = ? " ) @FilterDef( name="activeAccount", parameters = @ParamDef( name="active", type="boolean" ) ) @Filter( name="activeAccount", condition="{a}.active = :active and {ad}...

Hibernate JPA @SQLDelete Example

@SQLDelete The @SQLDelete annotation is used to specify a custom SQL DELETE statement for the currently annotated entity or collection. SQLDelete used for custom SQL statement for delete of an entity/collection. Custom CRUD @Entity(name = "Person") @SQLInsert( sql = "INSERT INTO person (name, id, valid) VALUES (?, ?, true) ", check = ResultCheckStyle.COUNT ) @SQLUpdate( sql = "UPDATE person SET name = ? where id = ? " ) @SQLDelete( sql = "UPDATE person SET valid = false WHERE id = ? " ) @Loader(namedQuery = "find_valid_person") @NamedNativeQueries({ @NamedNativeQuery( name = "find_valid_person", query = "SELECT id, name " + "FROM person " + "WHERE id = ? and valid = true", resultClass = Person.class ) }) public static class Person { @Id @GeneratedValue private Long id; private String name; @ElementCollection @SQLInsert( sql = ...

Hibernate JPA @Source Example

@Source The @Source annotation is used in conjunction with a @Version timestamp entity attribute indicating the SourceType of the timestamp value. The SourceType offers two options: DB Get the timestamp from the database. VM Get the timestamp from the current JVM. Source optional annotation in conjunction with Version and timestamp version properties indicating the source of the timestamp value. Database-generated version timestamp mapping @Entity(name = "Person") public static class Person { @Id private Long id; private String firstName; private String lastName; @Version @Source(value = SourceType.DB) private Date version; }

Hibernate JPA @SortNatural Example

@SortNatural The @SortNatural annotation is used to specify that the Set/Map should be sorted using natural sorting. SortNatural specifies in-memory Set/Map sorting using natural sorting. NOTE : Sorting is different than ordering (see OrderBy) which is applied during the SQL SELECT. For sorting based on a comparator, use SortComparator instead. It is illegal to combine SortComparator and SortNatural. Bidirectional natural sorted set @OneToMany(mappedBy = "person", cascade = CascadeType.ALL) @SortNatural private SortedSet<Phone> phones = new TreeSet<>(); @SortComparator(ReverseComparator.class) private SortedSet<Phone> phones = new TreeSet<>();

Hibernate JPA @SortComparator Example

@SortComparator The @SortComparator annotation is used to specify a Comparator for sorting the Set/Map in-memory. SortComparator Specifies in-memory Set/Map sorting using a specified Comparator for sorting. NOTE : Sorting is different than ordering (see OrderBy) which is applied during the SQL SELECT. For sorting based on natural sort order, use SortNatural instead. It is illegal to combine SortComparator and SortNatural. Unidirectional custom comparator sorted set @Entity(name = "Person") public static class Person { @Id private Long id; @OneToMany(cascade = CascadeType.ALL) @SortComparator(ReverseComparator.class) private SortedSet<Phone> phones = new TreeSet<>(); //Getters and setters are omitted for brevity } public static class ReverseComparator implements Comparator<Phone> { @Override public int compare(Phone o1, Phone o2) { return o2.compareTo( o1 ); } } @Entity(name = "Phone") public static class P...

Hibernate JPA @SelectBeforeUpdate Example

@SelectBeforeUpdate The @SelectBeforeUpdate annotation is used to specify that the currently annotated entity state be selected from the database when determining whether to perform an update when the detached entity is reattached. SelectBeforeUpdate should the entity's current state be selected from the database when determining whether to perform an update when re-attaching detached entities? Example : OptimisticLockType.DIRTY mapping example @Entity(name = "Person") @OptimisticLocking(type = OptimisticLockType.DIRTY) @DynamicUpdate @SelectBeforeUpdate public static class Person { @Id private Long id; @Column(name = "`name`") private String name; private String country; private String city; @Column(name = "created_on") private Timestamp createdOn; //Getters and setters are omitted for brevity } The main advantage of OptimisticLockType.DIRTY over OptimisticLockType.ALL and the default OptimisticLockType.VERSION ...

Hibernate JPA @RowId Example

@RowId The @RowId annotation is used to specify the database column used as a ROWID pseudocolumn. For instance, Oracle defines the ROWID pseudocolumn which provides the address of every table row. According to Oracle documentation, ROWID is the fastest way to access a single row from a table. Support for ROWID mapping feature of Hibernate. @RowId If you annotate a given entity with the @RowId annotation and the underlying database supports fetching a record by ROWID (e.g. Oracle), then Hibernate can use the ROWID pseudo-column for CRUD operations. Example : @RowId entity mapping @Entity(name = "Product") @RowId("ROWID") public static class Product { @Id private Long id; @Column(name = "`name`") private String name; @Column(name = "`number`") private String number; //Getters and setters are omitted for brevity } Now, when fetching an entity and modifying it, Hibernate uses the ROWID pseudo-column for the UPDAT...