Skip to main content

Posts

Showing posts with the label Hibernate

SpringDataJPA : One to Many Mapping in Spring Boot Hibernate JPA with Spring Data

Also Read One To One Mapping Let's create two entities/domains Employee and Department such that they have the following relation between them. Department has-many Employees which means an Employee can belong to only one Department and a Department can have many Employee and Department is the owner of the relation between the two. Owner of the relation means that Owner can exist without the dependent entity but dependent entity cannot stay without the owner entity . Dependent Entity of Relationship will containes the 'foreign key' ID of the Owner entity . In this case, Address will contian the Employee Id in >its table as shown in the table structure below. So a Department can exist without Employee but an Employee cannot be there without a Department. If you on deleting an Employee, the Employee-Department mapping will be removed on deleting a Department, all the employees in the department should be deleted. Employee.java package com.ekiras.domain; import jav...

SpringDataJPA : One to one Mapping in Spring Boot Hibernate JPA with Spring Data

Also Read One To Many Mapping Let's create two classes Employee and Address , such that they have the following relation between them. Employee has-a Address which means a one-to-one mapping between the two and Employee is the owner of the relation. Owner of the relation means that Owner can exist without the dependent entity but dependent entity cannot stay without the owner entity. Dependent Entity of Relationship will containes the 'foreign key' ID of the Owner entity . In this case, Address will contian the Employee Id in its table as shown in the table structure below. This means that Employee can stay without an Address but Address cannot stay without the Employee. In even more simpler words, If employee is deleted his address should also be deleted, but if address is deleted employee should not be deleted. Employee.java package com.ekiras.domain; import javax.persistence.*; import java.util.Date; /** * @author ekiras */ @Entity public class Employee { ...

SpringDataJpa : How to override the domain mapping defined in Parent Entity class with MappedSuperclass

Points To Remember Your Parent class should be annotated with @MappedSuperclass . Follow the Tutorial : How to handle Inheritence with Entities to know how to wrap common properties of entities to a base class. To override any property you must a. Apply the @AttributeOverride annotation on the class that need to override the property b. set name property of @AttributeOverride as the name of the field in super class. c. set the column property of @AttributeOverride to override the column definition of the attribute. Let's say our Base class looks as follows package com.ekiras.domain.base; import javax.persistence.*; import java.util.Date; /** * @author ekiras */ @MappedSuperclass public abstract class BaseDomain { @Id @GeneratedValue (strategy = GenerationType.AUTO) protected long id; @Temporal (TemporalType.TIMESTAMP) protected Date dateCreated; @Temporal (TemporalType.TIMESTAMP) protected Date lastUpdated; @Override public String toString (...

SpringDataJpa : How to handle inheritance with Entities

Points to Remember Mark your Base Entity class with annotation @MappedSuperclass . Define all common fields and their getter setters in this class. Make the base class abstract. Make all fields as protected so that they can be accessed in inheriting class without getters and setter. You can also define @PrePersist and @PreUpdate in this class. Fields that should be in the Base Entity Your Base Entity class should have only those field that need to be common for all your entities that will inherit this class. Sample Base Entity that you should use might look as follows package com.ekiras.domain.base; import javax.persistence.*; import java.util.Date; /** * @author ekiras */ @MappedSuperclass public class BaseDomain { @Id @GeneratedValue (strategy = GenerationType.AUTO) protected long id; @Temporal (TemporalType.TIMESTAMP) protected Date dateCreated; @Temporal (TemporalType.TIMESTAMP) protected Date lastUpdated; @Override public String...

Spring Boot : How to enable Hibernate SQL Logging using application.properties

How to enable Hibernate SQL Logging in Spring Boot using application.properties You can enable hibernate sql logging level to Debug. This will print the sql queries fired by hibernate. logging.level.org.hibernate.SQL=DEBUG Your complete SQL configuration may look like following spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost/ekiras spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver logging.level.org.hibernate.SQL=DEBUG

JPA : One to Many Mapping using Hibernate Spring Boot

STEP 1 :: Add the dependencies You need to add the following dependencies in your build.gradle file. compile('org.springframework.boot:spring-boot-starter-data-jpa') compile('org.springframework.boot:spring-boot-starter-jdbc') runtime('mysql:mysql-connector-java') STEP 2 :: Make Entity classes You need to create two entity QUESTION and TOPIC. Here the Topic Entity will have an annotation @OneToMany , this indicates the following This one topic can have many questions. All the questions will be deleted or updated when topic is deleted/updated. Its mapping is defined by Entity Question by the mapping of topic variable. It will give a list of all question of a topic when it is fetched If you do not need questions when topic is fetched then make fetch type as LAZY @OneToMany(cascade = CascadeType.ALL,mappedBy = "topic",fetch = FetchType.EAGER) private List questions; Here the Question entity will have the annotation @ManyToOne , ...

Hibernate : Make a field Non Updatable in an Entity

Points To Remember By default all the fields in the Hibernate Entity are updatable and insertable. To make a field non updatable in hibernate you nee to add the annotation  @Column(updatable = false) Make a field Non Updatable in an Hibernate Entity Suppose you have a User class and you want to make email as a non updatable field, all you need to do is add the  @Column(updatable = false)  annotation as shown in the example below. @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "email",updatable = false, nullable = false, unique = true) private String email; // GETTERS and SETTERS } Note : This only puts a hibernate level constraint , however you can still manually go and change the value of email by using db level queries.

How to Send Rest Response For Lazy fetched Hibernate Objects with Jackson

How to Send Rest Response For Lazy fetched Hibernate Objects with Jackson Just add the following class to your application and your jackson will be configured to send the JSON response for the LAZY fetched domain objects. You need to add the dependency  compile("com.fasterxml.jackson.datatype:jackson-datatype-hibernate4:2.6.1") @Configuration @EnableWebMvc public class HibernateAwareObjectMapper extends WebMvcConfigurerAdapter { //More configuration.... /* Here we register the Hibernate4Module into an ObjectMapper, then set this custom-configured ObjectMapper * to the MessageConverter and return it to be added to the HttpMessageConverters of our application*/ public MappingJackson2HttpMessageConverter jacksonMessageConverter(){ MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); //Registering Hibernate4Module to support lazy objects mapper.r...

Hibernate : How to get List of records of an Entity

How to get List of records in Hibernate // List all records public List<User> list(){ return sessionFactory.getCurrentSession() .createCriteria(User.class).list(); // List all records } // List records based on MAX public List<User> list(Integer max){ return sessionFactory.getCurrentSession().createCriteria(User.class) .setMaxResults(max).list(); } // List records with MAX records and OFFSET public List<User> list(Integer max, Integer offset){ return sessionFactory.getCurrentSession().createCriteria(User.class) .setMaxResults(max) .setFirstResult(offset) .list(); } // List records with MAX records and OFFSET and ORDER by id field of User class public List<User> list(Integer max, Integer offset){ return sessionFactory.getCurrentSession().createCriteria(User.class) .setMaxResults(max) ...

Hibernate : How to use @Temporal annotation

Points To Remember @Temporal annotation must be used with the persistent fields or properties of type java.util.Date  java.util.Calendar How to use @Temporal annotation @Temporal Annotation is defined as following @Target({ METHOD, FIELD }) @Retention(RUNTIME) public @interface Temporal { /** * The type used in mapping <code>java.util.Date</code> or <code>java.util.Calendar</code>. */ TemporalType value(); } So the TemporalType is an Enum and looks like following public enum TemporalType { DATE, TIME, TIMESTAMP } So @Temporal annotation can take three values DATE, TIME and TIMESTAMP . And it will create the following database ddl type. TemporalType Database DDL Type DATE date TIMESTAMP datetime TIME time If we the following class as Hibernate Entity package com.ekiras.domian; import javax.persistence.*; import java.util.Date; @Entity public class User { @Id @SequenceGenerator(name = "test") @GeneratedValue(strategy = GenerationT...

Hibernate : How to use @Column Annotation

Points To Remember @Column annotation is used to define the column name, type, constraints. It should be used with the fields either above the getter or above field declaration. The @Column annotation can take the following configuration. Property Type Default Value Description name Optional "" The name of the column. Defaults to the property or field name unique Optional false Whether the column is a unique key. nullable Optional true Whether the database column is nullable. insertable Optional true Whether the column is included in SQL INSERT statements generated by the persistence provider. updatable Optional true Whether the column is included in SQL UPDATE statements generated by the persistence provider. columnDefinition Optional "" The SQL fragment that is used when generating the DDL for the column. table Optional "" The name of the table that contains the column. If absent the column is assumed to be in the primary table. length Optional 255 The...

Hibernate : How to use @Id annotation

Points to remember There should be only one @Id annotation in a hibernate entity class. There should be at least one field specified as primary id. You can use different approaches for creating primary id using these  Primary Key Generation Strategies. How to use @Id annotation in Hibernate Taking the example in the previous example .  @Id  annotation tells the hibernate to @Id annotation tells the hibernate that this field will be the primary key of the table. @Id annotation class looks like the following @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Id { } If we do not add @Id annotation on any of the fields in Hibernate entity then you will get the following error. Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1249) at org.hibernate.jpa.boot.int...

Hibernate : How to use @Entity annotation

How to use @Entity annotation in Hibernate Suppose we want to make a User  domain with the following fields Id Name Age Address Gender Email Mobile We can create tell the hibernate to register this Domain class as a Hibernate Entity object by adding @Entity annotation  at the class level. package com.ekiras.domian; import com.ekiras.enums.Gender; import javax.persistence.Entity; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private Integer age; private String address; private Gender gender; private String email; private Long mobile; // GETTERS and SETTERS } So what the above line means is that, hibernate treats the class User as a Hibernate Persistence Entity. We will look at the  @Id and  @GeneratedValue annotations in a short while. @Entity annotation looks like the following @Documented @Target(TYPE) @Retention(RUNTIME) public @interface Entity...

Spring Boot Gradle MVC sample CRUD project

This is a sample Spring Boot Application that uses  JDBC Mysql JPA MVC Gradle Create Basic CRUD for Person Entity with JPA and Mysql Download from GitHub Project Structure  build.gradle View Maven Dependencies (pom.xml) here. buildscript { ext { springBootVersion = '1.2.5.RELEASE' } repositories { maven { url "http://repo.spring.io/libs-milestone" } mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") classpath("io.spring.gradle:dependency-management-plugin:0.5.1.RELEASE") } } apply plugin: 'java' apply plugin: 'eclipse-wtp' apply plugin: 'idea' apply plugin: 'spring-boot' apply plugin: 'io.spring.dependency-management' apply plugin: 'war' war { baseName = 'springboot' version = '0.0.1-SNAPSHOT' } sourceCompatibility = 1.7 targetCompatibility = 1.7 rep...

Hibernate : @Table Annotation

Points To Remember @Table Annotation is an annotation that is used to give the table level information. It can be uesd to specify the following Table name  (optional,default ="")- to set the name of the table in database Table schema  (optional,default ="")- to set the schema of the table in database Table catalog  (optional,default ="") -to set the catalog of the table Table Constraints  (optional,default = []) to set the constraints on the table. It belongs to the package javax.persistence.Table @Table( name="person", schema="ekiras", uniqueConstraints = {@UniqueConstraint(columnNames = {"id","email"})} ) public class Person { private Long id; private String name; private String email; // code } If you do not define the name  property of the  @Table annotation then the hibernate would have created table by name Person  but now it will create the table by name person . The person  table will have the unique...

How to execute a SQL query in grails

Points To Remember You need to inject the  SessionFactory  object in the service or the controller, where you want to use it. Get the current session from the session factory and execute the query in this session using  sessionFactory.getCurrentSession(). You can also execute the query in a new session by using  sessionFactory.openSession(). Executing SQL query in grails Person.groovy package com.ekiras.grails; class Person{ String username String email String password static mapping = { } static constraints = { username nullable: true password nullable: false, blank: false email nullable: false, blank: false } } PersonService.groovy package com.ekiras.grails; import org.hibernate.SessionFactory; import grails.transaction.Transactional import com.ekiras.grails.Person; @Transactional class PersonService{ SessionFactory sessionFactory; def listPersons(){ String query = "select distinct username from person"; def person...

Hibernate : fetch results using Orderby in Criteria Query

Syntax to use OrderBy in Hibernate Criteria Query The order can be specified using addOrder on a Criteria Object criteria.addOrder(Order.asc("propertyName")) criteria.addOrder(Order.desc("propertyName")) Order results according to an order in Hibernate  Suppose we have a class Category.java package com.ekiras.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="category") public class Category { public Category(){} public Category(Long id){ this.id = id; } public Category(Long id, String name){ this.id = id; this.name = name; } @Id @Column(nullable=false, name="id") @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(nullable=false, name="name") private String name; // Gett...

Hibernate Criteria Query to find List of Domain class.

Syntax to get List of domain Object list can be used on the Criteria object as shown below. criteria.list() How to get a List of a Domain class using Hibernate's Criteria Query. If we have a domain class Category  as shown below. Catgeory.class package com.ekiras.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="category") public class Category { public Category(){} public Category(Long id){ this.id = id; } public Category(Long id, String name){ this.id = id; this.name = name; } @Id @Column(nullable=false, name="id") @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(nullable=false, name="name") private String name; // Getters and Setters } We can get the list of all the categories ...

Pagination in Spring Hibernate Mvc application

Points To Remember Create a Pagination Taglib using this example . Add Bootstrap css and js in the jsp you want to do pagination and include the taglib in the jsp. Pagination in Spring Hibernate Application using Bootstrap Create a Domain Person. Create a Service PersonService Create a Dao PersonDao . Create a Controller PersonController . Create a Taglib PaginationTaglib. Person.java package com.ekiras.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="person") public class Person { public Person(){}; public Person(String name,Integer age){ this.name = name; this.age = age; } @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id") private Long id; @Column(name="name") private String name; @Column(name="age") private Integer age; ...

How to get results from a fixed position in Hibernate Criteria Query

Points To Remember Offset may be required to do pagination or get the results after a particular result from the database. Using offset you can define the first result to be included in the result set from the database.  You can use setFirstResult  on the CriteriaQuery  to set the first result that you want. Using offset to get the results SampleDAO.java @SuppressWarnings("unchecked") public List<Person> getCategories(Integer offset){ return getSession() .createCriteria(Person.class) .setFirstResult(offset!=null?offset:0) .setMaxResults(10) .list(); } This is how you can set the first result you want to fetch from the database. In this example we have set the first result and the maximum number of records that we need to fetch.