Skip to main content

Posts

Showing posts from September, 2015

Android : How to change application icon

Points To Remember Android saves the Application level Settings like App Icon, App Label etc in the AndroidManifest.xml file. Add your icon image as icon.png  in the drawable folder. How to change application icon Your Application structure looks like the following. Add the icon.png folder in the drawable  folder Open the Application > manifests > AndroidManifests.xml  file Add android:icon="@drawable/icon" in the application root. Your AndroidManifests.xml file should look like following <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.ekiras.activity" >       <application         android:allowBackup="true"         android:icon="@drawable/icon"         android:label="@string/app_name"         android:theme="@style/AppTheme" >         // Your activities are declared here         <activity>&l

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

Spring : How to get Current Profiles in Spring Application

Points To Remember You can use the Environment interface  in package org.springframework.core.env to get the current profiles in spring application. You can make use of the following methods to get the information about the profiles. acceptsProfiles(String ...profiles)  - returns if the profiles given in input is active. getActiveProfiles()  - Gives a list of profiles explicitly made active for this enviornment. getDefaultProfiles()  - gives a set of profiles to be active by default if no active profile is set explicitly. See how to set and configure profiles in spring. Must Read :: What are profiles in Spring boot. How to get Active Profiles in an Environment All you need to do is autowire  the Environmnet bean. call the getActiveProfiles method of the bean. package com.ekiras.config; import org.springframework.stereotype.Component; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; @Component class Test { @Autowired pri

SpringBoot : CORs Allow Custom Headers in Ajax calls

Points To Remember Add the comma separated Headers (standard and Custom headers) CORs Allow Custom Headers in Ajax calls $.ajax({ method : 'POST', url : 'url', headers: {'Custom-Header-1':'h1','Custom-Header-2':'h2'}, success: function(data){}, error : function(error){} }); @Component public class CorsFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Custom-Header-1 , Custom-Header-2, X-Auth-Token&q

SpringBoot : How to allow cross origin ajax calls to Spring application

How to allow cross origin ajax calls to Spring application Add the following class to your Spring or Spring Boot application. After adding this class you will be able to make ajax calls to your application. package com.ekiras.filter; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class CorsFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with"

Gradle : Task to add selected files to jar

Points To Remember You can create local variable in gradle with the type def, e.g def jarName = "ekiras" You can print variable with help of println  e.g println "jar name is -> $jarName Gradle task declaration syntax is  task taskName(type: taskType){} Task to add selected files to jar We will be writing two tasks for this First task -  compileFiles  -> this will compile all the files in the project and then save them to the build/classes/  folder of the project Second Task - makeJar  -> this will take all the compile files from the base folder and make a jar of these files in build/lib/  folder of the project. task compileFiles(type: JavaCompile) { println '>>>>>>>>>>>>>>>>>>>>> start compiling' source = sourceSets.main.java.srcDirs classpath = sourceSets.main.compileClasspath destinationDir = sourceSets.main.output.classesDir println '>>>>>>>>

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.internal.EntityManagerFacto

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 { String name() defa