Showing posts with label frameworks. Show all posts
Showing posts with label frameworks. Show all posts

Tuesday, September 25, 2018

Can you write the code using CriteriaQuery parameter in JPA hibernate?

[1] - CriteriaQueryParametersClientTest.java

package com.ishaan.client;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;
import org.hibernate.Session;
import org.hibernate.query.Query;
import com.infotech.entities.Person;
import com.infotech.util.HibernateUtil;

public class CriteriaQueryParametersClientTest {

public static void main(String[] args) {
String nickName="Sam";
try(Session session = HibernateUtil.getSessionFactory().openSession()) {
CriteriaBuilder builder = session.getCriteriaBuilder();

CriteriaQuery<Person> criteriaQuery = builder.createQuery(Person.class);
Root<Person> root = criteriaQuery.from(Person.class);

ParameterExpression<String> nickNameParameter = builder.parameter(String.class);
criteriaQuery.where(builder.equal(root.get("nickName"), nickNameParameter));

Query<Person> query = session.createQuery(criteriaQuery);
query.setParameter(nickNameParameter, nickName);

List<Person> resultList = query.getResultList();
for (Person person : resultList) {
System.out.println(person);
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

[2]- SaveDataClientTest.java:

package com.ishaan.client;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.infotech.entities.Person;
import com.infotech.util.HibernateUtil;

public class SaveDataClientTest {

public static void main(String[] args) {

SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = null;
try {
session = sf.openSession();
session.beginTransaction();

Person person1 = new Person();
person1.setName("Mark Bingel");
person1.setNickName("Mac");
person1.setAddress("Alameda Street Los Angeles");
person1.setCreatedOn(new Date());
person1.setVersion(1);

Person person2 = new Person();
person2.setName("Sean Murphy");
person2.setNickName("Sam");
person2.setAddress("Bank of Canada,234 Wellington Street");
person2.setCreatedOn(new Date());
person2.setVersion(1);

session.save(person1);
session.save(person2);

session.getTransaction().commit();

} catch (Exception e) {
e.printStackTrace();
}finally{
if(session != null){
session.close();
}
}
}
}

[3] - Person.java

package com.ishaan.entities;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

@Entity
@Table(name="Person")
public class Person {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private Long id;

    @Column(name="name")
    private String name;

    @Column(name="nickName")
    private String nickName;

    @Column(name="address")
    private String address;

    @Temporal(TemporalType.TIMESTAMP )
    @Column(name="createdOn")
    private Date createdOn;

    @Version
    @Column(name="version")
    private int version;
    
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getNickName() {
return nickName;
}

public void setNickName(String nickName) {
this.nickName = nickName;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public Date getCreatedOn() {
return createdOn;
}

public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}

public int getVersion() {
return version;
}

public void setVersion(int version) {
this.version = version;
}

@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", nickName=" + nickName + ", address=" + address
+ ", createdOn=" + createdOn + ", version=" + version + "]";
}
}

[4] - HibernateUtil.java 

package com.ishaan.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

/**
 * 
 * @author Ishaan
 *
 */
public class HibernateUtil {
  private static StandardServiceRegistry standardServiceRegistry;
  private static SessionFactory sessionFactory;

  static{
    if (sessionFactory == null) {
      try {
        // Create StandardServiceRegistry
        standardServiceRegistry = new StandardServiceRegistryBuilder()
            .configure()
            .build();
        // Create MetadataSources
        MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
        // Create Metadata
        Metadata metadata = metadataSources.getMetadataBuilder().build();
        // Create SessionFactory
        sessionFactory = metadata.getSessionFactoryBuilder().build();
      } catch (Exception e) {
        e.printStackTrace();
        if (standardServiceRegistry != null) {
          StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
        }
      }
    }
  }
  //Utility method to return SessionFactory
  public static SessionFactory getSessionFactory() {
  return sessionFactory;
  }
}

[5] - hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:4406/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>

<mapping class="com.ishaan.entities.Person"/>
</session-factory>

</hibernate-configuration>


[6] - pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ishaan</groupId>
  <artifactId>CriteriaQueryParametersExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
   <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- MySQL connector dependency -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
     <version>6.0.5</version>
    </dependency>
    
    <!-- Hibernate 5.2.12 Final dependency-->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.12.Final</version>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

click for more

Tuesday, June 26, 2018

Saving data to file using SpringBoot postman

pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.boot</groupId>
<artifactId>raja-boot</artifactId>
<version>1.0.1-Release</version>
<packaging>war</packaging>

<name>spring-boot</name>
<url>http://maven.apache.org</url>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>

<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- <dependency> -->
<!-- <groupId>org.springframework.boot</groupId> -->
<!-- <artifactId>spring-boot-starter-data-jpa</artifactId> -->
<!-- </dependency> -->

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-json -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>

</dependencies>
<build>
<plugins>
<!-- Package as an executable jar/war -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

2. SpringBootApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages={"com.boot"})
public class SpringBootApp {

public static void main(String[] args) {
SpringApplication.run(SpringBootApp.class, args);
System.out.println("spring boot application is running");
}
}

3. RestController.java
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.boot.entity.Student;

@org.springframework.web.bind.annotation.RestController
@RequestMapping("/api")
public class RestController {
@RequestMapping(value = "/ping/", method = RequestMethod.GET)
public String ping() {
  return "successsss !!";
}
@RequestMapping(value = "/create/", method = RequestMethod.POST)
@ResponseBody 
public String create(@RequestBody Student data) throws IOException {
File file = new File("/home/rajar/demo.txt");
FileOutputStream stream = new FileOutputStream(file);
OutputStreamWriter obj = new OutputStreamWriter(stream);
BufferedWriter br  =new BufferedWriter(obj);
br.write(data.getName().toString());
br.append("\n");
br.write(data.getId());
br.close();
  return "<h2>rajjjjjjaaaaaa !!</h2>";
}
}

4. Student.java

import java.io.Serializable;

public class Student implements Serializable {

private String id;
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}
}

Saturday, May 26, 2018

How do I run spring boot artifact (jar/war/ear)?

Problem statement: How do I run an artifact using cmd?

  • running an artifact as a package/zip application:

step-1: open cmd
step-2: go to the path where artifact is present in your machine
step-3: fire the following command
            $ java - jar myapp-1.0.0-SNAPSHOT
step-4: enter
step-5: now type the url to access through your browser

  • Using maven plugin:

step-1: open cmd
step-2: go to the path where artifact is present in your machine
step-3: fire the following command
            $ mvn spring-boot:run
step-4: enter
step-5: now type the url to access through your browser

Wednesday, May 23, 2018

dependency injection (DI) vs inversion of control (IoC) ?

Problem statement: what do you mean by dependency injection (DI) and inversion of control (IoC)?
  • IoC (Inversion of Control): giving control to the container to get instance of an object is called inversion of control, meaning instead i'm creating the object using new operator, let container do that for me.
  • DI (Dependency Injection): way of injecting (providing) properties to an object is called DI.
  • Types of Dependency Injection
  1. Constructor Injection
  2. Setter/Getter Injection - property in xml
  3. Interface Injection (spring does not support)

Friday, May 18, 2018

What do you mean by spring module?

Problem statement: what are the spring's modules have you used in you projects?



  1. Spring Core module [ Beans, Context ]
  2. Spring Web module [ MVC, Servlet ]
  3. Spring DAO module [ ORM ]
  4. Spring Intergrations [ JMS ]
  5. Spring AOP [ Aspect Oriented Programming ]

what do you mean by spring mvc architecture?

Problem statement : what is the architecture of your project if you use spring mvc pattern?



Step 1: First request will be received by DispatcherServlet
Step 2: DispatcherServlet will take the help of HandlerMapping and get to know the Controller class name associated with the given request
Step 3: So request transfer to the Controller, and then controller will process the request by executing appropriate methods and returns ModelAndView object (contains Model data and View name) back to the DispatcherServlet
Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the actual view page
Step 5: Finally DispatcherServlet will pass the Model object to the View page to display the result

Tuesday, May 15, 2018

How do you set hibernate second level cache with an example

Problem statement: What is hibernate second level cache?
Caching is facility provided by ORM frameworks which help users to get fast running web application, while help framework itself to reduce number of queries made to database in a single transaction. Hibernate also provide this caching functionality, in two layers.
  • Fist level cache: This is enabled by default and works in session scope. Read more about hibernate first level cache.
  • Second level cache: This is apart from first level cache which is available to be used globally in session factory scope.
Above statement means, second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory.
It also means that once session factory is closed, all cache associated with it die and cache manager also closed down.
Further, It also means that if you have two instances of session factory (normally no application does that), you will have two cache managers in your application and while accessing cache stored in physical store, you might get unpredictable results like cache-miss.
Region Factory:
We add the Ehcache region factory implementation to the classpath with the following Maven dependency:
   <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-ehcache</artifactId>
    <version>5.2.2.Final</version>
</dependency>

Enabling Second-Level Caching:

With the following two properties we tell Hibernate that L2 caching is enabled and we give it the name of the region factory class:
  1. hibernate.cache.use_second_level_cache=true
  2. hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
For example, in persistence.xml it would look like:
1
2
3
4
5
6
7
<properties>
    ...
    <property name="hibernate.cache.use_second_level_cache" value="true"/>
    <property name="hibernate.cache.region.factory_class"
      value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/>
    ...
</properties>
To disable second-level caching (for debugging purposes for example), just set hibernate.cache.use_second_level_cache property to false.

Making an Entity Cacheable

In order to make an entity eligible for second-level caching, we annotate it with Hibernate specific @org.hibernate.annotations.Cache annotation and specify a cache concurrency strategy.
Some developers consider that it is a good convention to add the standard @javax.persistence.Cacheable annotation as well (although not required by Hibernate), so an entity class implementation might look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Foo {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID")
    private long id;
    @Column(name = "NAME")
    private String name;
     
    // getters and setters
}
For each entity class, Hibernate will use a separate cache region to store state of instances for that class. The region name is the fully qualified class name.
Cache Concurrency Strategy:

org.hibernate.cache.CacheFactorypublic static final StringNONSTRICT_READ_WRITE"nonstrict-read-write"public static final StringREAD_ONLY"read-only"public static final StringREAD_WRITE"read-write"public static final StringTRANSACTIONAL"transactional"

Based on use cases, we are free to pick one of the following cache concurrency strategies:
  • READ_ONLY: Used only for entities that never change (exception is thrown if an attempt to update such an entity is made). It is very simple and performant. Very suitable for some static reference data that don’t change
  • NONSTRICT_READ_WRITE: Cache is updated after a transaction that changed the affected data has been committed. Thus, strong consistency is not guaranteed and there is a small time window in which stale data may be obtained from cache. This kind of strategy is suitable for use cases that can tolerate eventual consistency
  • READ_WRITE: This strategy guarantees strong consistency which it achieves by using ‘soft’ locks: When a cached entity is updated, a soft lock is stored in the cache for that entity as well, which is released after the transaction is committed. All concurrent transactions that access soft-locked entries will fetch the corresponding data directly from database
  • TRANSACTIONAL: Cache changes are done in distributed XA transactions. A change in a cached entity is either committed or rolled back in both database and cache in the same XA transaction
Cache Management:
If expiration and eviction policies are not defined, the cache could grow indefinitely and eventually consume all of available memory. In most cases, Hibernate leaves cache management duties like these to cache providers, as they are indeed specific to each cache implementation.
For example, we could define the following Ehcache configuration to limit the maximum number of cached Foo instances to 1000:
1
2
3
<ehcache>
    <cache name="org.baeldung.persistence.model.Foo" maxElementsInMemory="1000" />
</ehcache>

Query Cache:


Results of HQL queries can also be cached. This is useful if you frequently execute a query on entities that rarely change.
To enable query cache, set the value of hibernate.cache.use_query_cache property to true:
1
hibernate.cache.use_query_cache=true
Then, for each query you have to explicitly indicate that the query is cacheable (via an org.hibernate.cacheable query hint):
1
2
3
entityManager.createQuery("select f from Foo f")
  .setHint("org.hibernate.cacheable", true)
  .getResultList();

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...