Hibernate

Hibernate – Tutorials & Examples

Hibernate
Hibernate All Annotations - Tutorials & Examples @Embeddable: This annotation can be used for the joining tables, by default it is not even necessary with hibernate, but if your intermediate joining table needs any other addtional columns to be added, then you must have @Embeddable annotated class. Do remember, in spring boot projects, we used to create repository for all the entity files, so even though we have embedded class separately, we should not create repository classes for this.   @Entity: This is the main annotation to link your class with your tables. Eg: [java] @Entity public class Coupon extends BaseEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column...

Developers Repeated Mistakes

Articles, Errors and solutions, Hibernate, Java
In this post we are going to discuss about the repeated mistakes of developers during design/implementation/planning etc. This is just a sudden thought process, so this post will grow on my day to day experience and research wise only. Feel free to comment your repeated mistakes to add it to this master list. In Hibernate/Databases: While creating/planning a column for description, we forget to define the length of values it can hold or even forget to think such scenarios. So always think about the value length for each and every column to design a proper optimistic design approaches: Bad: Here it can hold only till the default size of 255 length, where as, this field may get the value of length more than 255 as well, in that case this fails and all these type of issues can ...

How to get JPA Project option in Eclipse STS ?

Hibernate, Tools
How to get JPA Project option in Eclipse STS ? By default JPA project option is not there when you check under New project in STS eclipse. To make it available install hibernate tools plugin(which is currently Jboss Tools)     Now you will be able to create the JPA Project,   Could not find Database perspective in your eclipse ? ThenĀ  you may not have installed the below plugin, which could have caused database perspective issue in your eclipse. https://stackoverflow.com/questions/7923041/i-dont-have-database-development-perspective-in-eclipse-java-se-ide   How to generate JPA entities from the MySQL Database ? First you need to create the JPA Project (STS New -> JPA Project), not able to see the JPA Project option, then you must install Jbo

GenerationType.IDENTITY vs GenerationType.SEQUENCE vs GenerationType.AUTO

Hibernate
GenerationType.IDENTITY vs GenerationType.SEQUENCE vs GenerationType.AUTO: In hibernate for the primary key/auto generated id value column we used to annotate @GeneratedValue with strategy as either of these, GenerationType.IDENTITY 2. GenerationType.SEQUENCE 3. GenerationType.AUTO   It is highly important to understand the difference between these generation types to make it fit in the right place. Suppose you have two tables namely store and coupon, store id is a primary key in store table and foreign key in coupon table. Store table: store_id | store_name | store_url   Coupon table: coupon_id | coupon_name | store_id 1. GenerationType.IDENTITY In the above use case if you mention GenerationType.IDENTITY in store_id and coupon_id field in both store ...

Understanding @JsonIgnore with JPA Hibernate

Hibernate
Understanding @JsonIgnore with JPA Hibernate @JsonIgnore Ignores from serialization and deserialization to and from JSON. Which means if you are calling REST API from anywhere then your attribute will not be present in JSON request/responses. But it will be persisted by JPA persistence.   I have Coupon and Category Model with Many to Many mapping: Here in coupon model I have category model with many to many mapping along with JsonIgnore annotation. So Here when I try to save coupon model then categories also saved, but When I try to retrieve coupon model then the categorylist is missing in the json response. If you remove @JsonIgnore annotation from categoryList field then the category lists attribute will be available inside every coupons.   Coupon.java: [j...

Understanding @Temporal and @JsonFormat in JPA Hibernate

Hibernate
Understanding @Temporal and @JsonFormat in JPA Hibernate Many of us prefer to use varchar even for date fields due to difficulty of date related db operations. But it is strongly not recommended to use varchar for date fields and highly advicable to use datetime or timestamp in MySQL. Today we are going to see how to use datetime field with hibernate, also it displays date and time, but I want to display only date in UI. So lets see what should be done for this requirement.     What is @Temporal? @Temporal is a JPA annotation used to store either TIME, DATE or TIMESTAMP in database table. Format can be defined using TemporalType. DATE, TIME AND TIMESTAMP are available temporaltypes. By default date field maps to sql.date but util.date is highly recommended in jav...

Spring Boot + EhCache Hibernate Working Example

Frameworks, Hibernate
Spring Boot + Ehcache Hibernate Working Example: When I was trying to populate JSON records in my angular app (just 1885 records only), it took around 11 seconds and in angular side I am just populating in the datatable. So I thought to implement ehcache with spring boot to make it faster. After implementing that successfully I am really surprised because it took around 300ms only to load same number of records (1885 records). Also no query will run from second time, until you modify something. Implementation steps in Overview: 1. Add org.springframework.boot and net.sf.ehcache to your pom.xml 2. Create ehcache.xml under resources folder of your spring boot project. 3. Add ehcache file to your application.properties 4. Add @EnableCaching to your spring startup java class. 5....

[Resolved] Illegal attempt to dereference path source [null.categoryList] of basic type

Errors and solutions, Hibernate
[Resolved] Illegal attempt to dereference path source [null.categoryList] of basic type This issue may happen for various use cases, I have explianed my usecase with the explantion, hope it helps someone.   Issue code: [java] Expression catInExp = couponRoot.get("categoryList").get("categoryName"); Predicate categoryInPredicate = catInExp.in(tempCategoryNamesSelected); allPredicates.add(categoryInPredicate); [/java]   Code Fixed: [java] Expression catInExp = couponRoot.join("categoryList").get("categoryName"); Predicate categoryInPredicate = catInExp.in(tempCategoryNamesSelected); allPredicates.add(categoryInPredicate); [/java]   My Coupon Model: [java] @Entity public class Coupon implements Serializable{ @ManyToMany private Set cate...

How to avoid implicit cross joins in JPA ?

Frameworks, Hibernate
How to avoid implicit cross joins in JPA ? When you join two tables and trying to select (column select) from the child table then you will come across this implicit cross join issues. For example we have two entities namely store, coupon and mapping follows, Store Entity: [java] @Entity public class Store { @OneToMany(mappedBy = "store") private List couponList; public Long getStoreId() { return storeId; } } [/java]   Coupon Entity: I have created one empty and one long argument constructor for coupon entity class. Because I want to select couponId after join and criteriaQuery.multiselect() requires the equivalent constructor to be available already in the entity. [java] @Entity public class Coupon { public Coupon(){ } Coupon(Long couponId){ thi...

Join two tables using Hibernate in Spring Boot Example

Frameworks, Hibernate
Join two tables using Hibernate in Spring Boot Example: Many enterprise applications whichever using hibernate uses sql queries only for joins still and uses hibernate only for save/update operations. Today we are going to see how to use hibernate to join two tables. We are going to see how to get count(*) using hibernate along with group by function in hibernate projections. How to create hibernate session from EntityManager? Use @PersistenceContext annotation to get entityManager object. EntityManager can be used to get the hibernate session using getDelegate() method.   [java] @Service public class StoreServiceImpl implements StoreService { @PersistenceContext private EntityManager entityManager; @Override public List getAllStoresWithCount() { // getting hib...