Posts

Showing posts with the label Hibernate

What is MappedSuperClass in hibernate ?

Image
MapperSuperClass ·         A mapped superclass has no separate table defined for it. ·         Designates a class whose mapping information is applied to the entities that inherit from it.  ·         A class designated with the  MappedSuperclass  annotation can be mapped in the same way as an entity except that the mappings will apply only to its subclasses since no table exists for the mapped superclass itself.  ·         When applied to the subclasses the inherited mappings will apply in the context of the subclass tables.  ·         Mapping information may be overridden in such subclasses by using the  AttributeOverride  and  AssociationOverride  annotations or corresponding XML elements. ·         It avoids the cod...

org.hibernate.HibernateException: No Session found for current thread

I am working one Spring MVC project in which I have integrated Spring with hibernate and most of the time, I use to get this error message while performing database operation .. org.hibernate.HibernateException: No Session found for current thread Reason : This is happening because I have missed declaring the transaction in my Spring Application. sessionFacory needs transaction to work. Solution : Define transaction manager in your Spring configuration file. Here is my spring-config.xml file : < bean id = "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" > < property name = "driverClass" value = "${db.driverClassName}" /> < property name = "jdbcUrl" value = "jdbc:mysql://${db.host}:${db.port}/${db.name}" /> < property name = "user" value = "${db.username}" /> < property name = "password" valu...

How to Map a list of strings with JPA/Hibernate annotations ?

Image
Yesterday while working on my project, I got one requirement where I need to store list of Array into the database, I checked on Google, went through various site but didn't get much information. Everyone talks about creating new entity and do onetomany relationship BUT I wanted to create a collection of basic types. Finally I come across @ElementCollection annotation provided by JPA 2.0 which resolves my problem. Problem : Input JSON which we need to store in DB: { "schemas": ["urn:scim:schemas:core:1.0", "urn:scim:schemas:extension:enterprise:1.0"] }            Where schemas is Array of String. Solution : Just add following annotation in your POJO i,e @ElementCollection @CollectionTable(name = "SCIM_SCHEMAS", joinColumns = @JoinColumn(name = "SCHEMA_ID")) @Column(name = "SCIM_SCHEMA") private List<String> schemas; It will create the table named "SCIM_SCHEMAS" having columns 'SCHE...

Hibernate Error - Caused by: org.hibernate.DuplicateMappingException: duplicate import:

In hibernate, You cannot have two classes with the same name in the same or different packages else you will get an error at runtime like " Caused by: org.hibernate.DuplicateMappingException: duplicate import: ....(try using auto-import="false ")" I have resolved this issue by adding property name on the Entity annotation. Let us suppose I have Meta class in two different packages "com.database.user" and "com.database.group', you can resolve it as : package com.database.user @Entity( name= "com.database.user" ) @Table(name="USER_META") public class Meta package com.database.group @Entity( name= "com.database.group" ) @Table(name="GROUP_META") public class Meta There must be some other ways too to resolve this issue, So please feel free to share it :)

Hibernate Configuration

To inform Hibernate from where to find mapping information of Java classes to database tables or configuration setting related to database, All such information is usually supplied by Hibernate Configuration Object. It is managed by an instance of org.hibernate.cfg.Configuration. An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application’s Java types to an SQL database. The mappings are compiled from various XML mapping files or from Java 5 Annotations. Hibernate provides following types of configurations hibernate.cfg.xml – A standard XML file which contains hibernate configuration and which resides in root of application’s CLASSPATH  hibernate.properties – A Java compliant property file which holds key value pair for different hibernate configuration strings.  Programmatic configuration – This is the manual approach. The configuration can be defined in Java class.  1. hibernate.cfg.xml : The hibernate.cfg.xml file...

What is Hibernate ?

Image
What is Hibernate ? Hibernate is an  open source java based library used to work with relational databases.  The term Object/Relational Mapping refers to the programming technique for converting data between relational databases and object oriented programming languages such as Java, C# etc. It is a very powerful ORM solution build on top of JDBC API. It was initiated by Gavin King in 2001. It is a persistence framework which is used to store and retrieve data from database. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application Hibernate  makes use of persistent objects called POJOs (Plain Old Java Objects). Hibernate maps Java classes(POJO) to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks. These objects works as a data carrier called DTO (Data Transfer Object). They are used to carry data between diffe...

What is Hibernate Caching?

Image
In a typical application, you perform lot of operations like instantiate objects, load object from the database and so on. Sometime in multiuser application you may face a situation in handling multiple call of databases. Hibernate offers caching functionality which is designed to reduces the amount of necessary database access. This is a very powerful feature if used correctly. It increases your application performance and works between your application and the database as it avoids the number of database hit as many as possible. Hibernate Cache Types : Hibernate uses different types of caches. Each type of cache is used for different purposes. Let us first have a look at this cache types. First level cache Second level cache Query level cache 1. First level cache : First-level cache is the session cache and is always Associates with the Session object. Hibernate uses this cache by default. The Session object keeps an object under its own cache before committing to th...

How to integrate Liquibase with Spring and Hibernate ?

Image
A sample tutorial on how to integrate Liquibase with Spring and Hibernate. While writing this tutorial, I have added javadoc in the code for better understanding and I believe You already have good knowledge on Spring and Hibernate. The main motto of this tutorial is to give an idea on how you can integrate Liquibase with Spring and Hibernate. If you are new to Liquibase : Click Here To integrate liquibase into your project, you need liquibase jars, So  download it before starting the project. I have created an application named "SHLIntegration". The Structure of the project is as follows : The dependencies are also listed here: Lets start with Employee class : 1. Create Employee class having getter/setter and add proper JPA annotation to each variable as below.   public class Employee {     @Id     @GeneratedValue     @Column(name="EMPLOYEE_ID")     private long id;     @Column...

Error:No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

To solve this problem. You have to do two things: 1. mark the DAO as transactional or function which is doing database call like:   @Transactional    public class EmployeeDaoImpl  extends DaoImpl implements EmployeeDao{  ///// }            OR @Transactional     public long addEmployee(Employee employee) {         System.out.println("Employee:"+employee );         long id = employeeDao.addEmployee(employee);         System.out.println("Id1: " );         return id;     } 2. Enable the annotation driven transcation management in applicationContext.xml (where your beans are defined): <beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="ht...