Tuesday, 11 April 2017

JPA

ref. to Spring Data JPA

Spring Data

Special feathers

1. Spring Query DSL Data Extension


Benefits of Using JPA

1. Productive, cardinality relationships.
2. Independent of underly database diabetes. Increasing code portabilities.
3. Caching. free to have.  cache holding all entities, and maintain transactions.
4. JPA may generate efficient SQL queries



Persistence

'Persistence' means that the data may be physically stored for retrieving, processing, transforming, or analyzing even the application life cycle has reached the end of the life cycle.


ORM

Java data model is created according to the object-oriented principle. However, in the database, all tables are related to each other via foreign keys and cardinality relationships.

ORM is about how mapping a Plain Java Old Object (POJO) into a relational database table. One object(instance) stands for a row in a database table.  Its attributes are persisted into table columns, excluding ones modified by 'transient'.

Entities

An entity class is a POJO decorated by annotation @Entity. It must follow the following requirements.
  •  It is not inherited from any framework class or interface.
  • The class must be annotated with the Entity annotation.
  • The class must have a public or protected, no-argument constructor. The class may have other constructors.
  • The class must not be declared final. No methods or persistent instance variables must be declared final.
  • If an entity instance is passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement the Serializable interface.
  • ?It may be an abstracted class, which is persisted by its derivatives
  • ?An entity may be extended from an abstract class; abstract class will be a part of the table.
  • ?An entity may be extended from another entity.
  • An entity may be extended from a non-entity class, but the non-entity class is not included in the table.
  • An entity may be extended from a non-entity class but decorated by annotation @MappedSupperClass. The superclass will be included as a part of the table. 
  • Instance attributes must be declared as private, protected, or package-private and can be accessed directly only by the entity class’s getters and setters.
Entity Relationships

Entity relationships(cardinality) are used to describe the instance relationships like one customer may have many orders, one customer must have one address, or one student is enrolled in many courses, meanwhile, a course may be registered by many students, etc.

@OneToOne(owning side can be any side)
@OneToMany and @ManyToOne(owning side at many)
@ManyToMany(@JoinTable)

Fetch types: lazy or eager.
to-one is by default eager.
to-many is by default lazy.

@JoinColumn (owning side, keeping the foreign reference.)
@Mapped (inverse side)

Instance relationship may be bidirectional or unidirectional, describing the dependencies of instances. For a bidirectional relationship, both instances are able to access each other. So they both need to keep a reference that points to another. For a unidirectional relationship, only one side of both instances needs to access the instance at the anther side.

How these instance relationships are mapped into relational database tables?
For bidirectional instance relationships: a designer must know which entity keeps the foreign key. It is called the owning side, thus the opposite side is called the inverse side.

Owning side is annotated by @JoinColumn. It declares a column to store a foreign key, which points to the inverse side. It is also called Children points to the Parrent. 

Inverse side is annotated by @OneToMany(mappedBy = "propertyNameAtOwningSide")
mappedBy means its reference is kept at the owning side as a foreign key.
owning: annotated by @ManyToOne @JoinColumn
inverse: annotated by @OneToMany(mappedBy)
  • One to Many:  Many-side is always owning side, one side is an inverse side(mapped by).
  • One to One: the owning side corresponding to the side to store the foreign key. 
  • Many to Many: owning side at the conjunction table. 

Inverse side
@Entity
@Table(name = "LISTER")
public class Lister extends User {

    @OneToOne(mappedBy = "lister") //inverse side 
    private Yard listedYard;

Owning side:
    @OneToOne
    @JoinColumn(name = "Lister_ID_FK", referencedColumnName = "USER_PK")
    protected Lister lister;

Unidirectional relationship: two entities, only one entity has a field to keep a foreign key to another entity. So it has only the owning side, which should be defined as the following. The key point is to declare the joined column.
    
    @OneToOne
    @JoinColumn(name = "ADDRESS_ID_FK", referencedColumnName = "ADDRESS_ID_PK")
    protected Address address; //owning side keeping FK

Persistence Context

The persistence context is a set of entity instances, which are accessed via an interface, an entity manager. We may manage underlying entities using this interface. The persistence context serves as a first-level cache, buffering the entity instances.

Within the persistence context, the entity instances' lifecycle is managed. An entity instance has four states, i.e. new, managed, removed, or detached.

New state: when an entity is instantiated at the application. It enters the new state.
Managed state: when the instance is persisted, it becomes managed in the persistence context. 
Removed state: when the entity instance is set to be removed, after flushing, its counterpart is deleted from the DB.
Detached state: a managed entity instance becomes not managed, and detached from the PC. 

The EntityManager API is used to create and remove persistence instances, to find entities by their primary key, and query over entities.




Primary Key

The primary key may uniquely identify an entity(entry), thus the entry can be located and fetched back. A primary key could be simple(one field) or composite(multiple fields).

The simple primary key is defined by an annotation @Id 
@Id: Primary key
@GeneratedValue(default strategy = auto-generated)

The composite primary key is defined by an annotation @EmbeddedId, meanwhile, a composite primary key is defined by a  class, decorated with annotation: @Embedable

Large Objects

@Lob(large object): designates BLOB(binary large objects) or CLOB(character large objects)
@Basic: designates the fetching type
BLOB: byte[] Byte[]
CLOB: char[] Characeter[]

Inheritance Mapping 

There are four types to map inheritance strategies.

Mapped Superclass:  

@MappedSuperClass: Table created for each subclass, but not for the superclass; the superclass will be part of the subclass table.

Pros: it is the easiest way to map inheritance; 
Cons: cannot query all superclass in one kick, but having to query from subclass tables one by one.

Single table: 


Table per class:



Joined table:

Each class in the hierarchy is mapped to an independent database table. Superclass and subclasses are designated as Entities; however, the subclass doesn't hold the fields of the superclass. In the database, they are mapped to their own table.






Dealing Collection of Objects

I think there are two ways to handle a collection of objects.
If an entity contains a collection of a basic type of embedded classes, then using the javax.persistence.ElementCollection ( targetClass, fetch) annotation. Otherwise from a performance view, it would be better to carry out in a one-to-many relationship.
@Entity
public class Person {
    ...
    @ElementCollection(fetch=EAGER)
    protected Set nickname = new HashSet();
    ...
}
Collections may be beyond the List, and Set.

Collections of entity elements and relationships may be represented by java.util.Map collections. A Map consists of a key and a value.

When using Map elements or relationships, the following rules apply.

If the Map value is an entity and part of a many-to-many or one-to-many unidirectional relationship, it will be mapped as a join table in the underlying database. A unidirectional one-to-many relationship that uses a Map may also be mapped using the @JoinColumn annotation.

If the entity is part of a one-to-many/many-to-one bidirectional relationship, it will be mapped in the table of the entity that represents the value of the Map. If generic types are not used, the target entity attribute of the @OneToMany and @ManyToMany annotations must be set to the type of the Map value.

@Embeded  (Entity)
@Embedable (Plain Java Class)

@ElementCollection


@Column: designates a database table column.
@Enumrated: designates a persistent attribute that is an enumeration type.

@Transient (a field having no need to be persisted)





Creating Auditing Using Spring JPA

For a large-scale application, it must track when an entity was created and modified and which user did it.

Spring data automatically do that tracking for you
There are two ways.
1. Decorating Entity with predefined Annotations.

@CreatedDate  : the entity is first persisted
@Column
private ZonedDateTime createdAt;

@LastModifiedBy: the entity's update was last persisted.
@Column
private User updatedBy;

@CreatedBy: an injected user who created the record
@Column
private User createdBy

@LastModifiedDate:  the date last modified.
@Column
private  ZonedDateTime lastModified

2. Entity entends from AbstractAuditable Implements Auditable

@Bean SpringSecurityAuditorAware


Managing Transactions

Required
Supports
Mandatory
Never

References: 

Saturday, 18 March 2017

String equality using "==" or equal to

The right way to compare two string equality, is to use 'equal to' method, but not "==", for it compares the reference equality but not the content of the string.

The following example is able to demonstrate the point above.
Both s1 and s2 have the same reference in the memory, i,.e. pointing to the same char block in the string pool. meaning that, the same string instance could be re-used as it is found in the string pool. Therefore, both s1 and s2  variables are referred to the same string instance. On this case, "==" may give correct result.

However, for s3 and s4, the s4 has been pointed to a newly created string instance in the heap memory; so on this case s3 and s4 are pointed to different references; "==" test gives a false result, even though s3 and s4 contain the same text content.

So, using equal to method is a safe way to compare two strings, for in this method all char value are compared one by one. 


/**
 *
 * @author YNZ
 */
public class StringEqual {
    
    public static void main(String ...  args){
        //string pool, in perm memory
        String s1 = "hello world";
        String s2 = "hello world"; 
        System.out.println(s1==s2);
        
        //new string in heap memory
        String s3 = "i am here";
        String s4 = new String("i am here");
        System.out.println(s3==s4);
        
    }
    
}


run:
true
false
BUILD SUCCESSFUL (total time: 0 seconds)



Friday, 11 November 2016

Inversion of Control(IoC) and Dependency Injection(DI)

IoC is a design principle, and DI is its implementation. Its main purpose, in my understanding, is to avoid instantiating instances within classes, i.e. aggregation or composition, a sort of strong association.

Traditionally, the logic is controlled by a custom-written code, where reusable procedures or modules are invoked in a sequence. By this way, the independent units have to become dependent on each other. Certainly, those independent units can be manipulated in a container, where they can be externally instantiated in runtime as they are invoked. It is a way to decouple the dependencies of units.

Spring framework provides this sort of IoC container. It instantiates Java plain classes(also called Spring beans) in runtime and giving references to their consumers. It is termed dependency injection(DI), which can be configured in ether a configuration class or by a xml file located in the source folder. It declares which implementation should be instantiated as in runtime,

In Spring there are two ways to configure this sort of external instantiation, i.e. in a Spring context where a bean is instantiated and ready by accessed by the client code. Which bean should be instantiated in such a Spring context, it is a client responsibility to define. It could be defined in a XML file located in source folder; or in a configuration class decorated by annotations.

a. by a configuration class

package Configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import services.EmailService;
import services.MessageService;

@Configuration
@ComponentScan(value={"Consumer"})
public class DIConfiguration {
 @Bean
 public MessageService getMessageService(){
  return new EmailService();
 }
}

b. by a XML configuration file. 

 <?xml version="1.0" encoding="UTF-8"?>  
 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
      <bean id="MyXmlApplication" class="Consumer.MyXMLApplication">  
           <constructor-arg>  
                <bean class="services.TwitterService"></bean>  
           </constructor-arg>  
      </bean>  
 </beans>  

Tuesday, 13 September 2016

Java Enum

The purpose of using enum is to constrain user inputs from a limited set of instances. 

Implicitly, Enum is a final class that extends from a Java abstract Enum class.  The enum has some implicit operations done by java compiler.  The compiler adds a static block in order to initialise all public static constants. By default, the enum class inherits a two-argument constructor from its superclass, and it includes the name and ordinal of the constant. Enum name() and toString() gives the same values, and Enum instance is ordered by its definition, and thereby constants cannot be sorted by an external sorting algorithm. 

Java enum cannot extend from other classes; for it implicitly extends abstract java.lang.Enum class. However, a Java enum can implement many interfaces. Java enum cannot be extended, because it is defined as a final class implicitly. 

Enum name(), hashCode() method is a final method, but toString() is not, so toString is allowed to be overridden. 

the enum allows adding extra attributes for each constant.
the enum allows private or default-access level constructors.
the enum cannot define constructors with a public or protected access level.
the enum allows set/get methods to access extra attributes on each constant.

An enum can define an abstract method. just ensure to override it for all your enum constants.
The enum method values are initialised in its super-class static block, it contains all defined enum constants.

Constants may not be followed by a semicolon if there is no other variables or methods defined inside this enum body. 

Here I created a simple example, which defines all directions, i.e. east, west, south, north; and I give each direction an extra attribute, i.e. degree. It can be initialized by its private constructor.

The following example shows that Enum value and attributes can be initialized by its constructors.
The toString() method can be overridden; it offers a convenient way to show each value and its attributes by one kick. 

One interesting thing, when I use Enum in the switch body, it doesn't need Enum identifier to refer to its own values. I guess the java compiler is becoming smarter and smarter. It can infer from switch input argument type itself. Once it finds an Enum type, then it will ignore the Enum identifier.

A constant specific class body defines overriding methods for a particular enum constant. 

Where can you define an enum? 
Enum can be independent, or a member of a class or an interface. However, Enum cannot be local within a method.



/*
 * In Java, Enum is a class type. 
 * 
 * 
 */
package Enum;

import java.util.Arrays;

/**
 *
 * @author YNZ
 */
public enum Direction {
    EAST(10), SOUTH(20), WEST(40), NORTH(30);
    
    //Enum constructor must be private or pakage-private(default access modifier)
    private Direction(double degree) {
        this.degree = degree;
    }

    private Direction() {
        this.degree = 0;
    }

    public static Direction getEAST() {
        return EAST;
    }

    public static Direction getNORTH() {
        return NORTH;
    }

    public static Direction getWEST() {
        return WEST;
    }

    public double getDegree() {
        return degree;
    }

    public static Direction getSOUTH() {
        return SOUTH;
    }

    @Override
    public String toString() {
        return this.name() + " " + this.getDegree();
    }
    
    //init. once as it is contructed. 
    private final double degree;
}


class UsingEnum {

    public static void main(String[] args) {
        System.out.println(Direction.EAST);
        Direction d = Direction.valueOf("EAST");
        System.out.println("" + d);
        System.out.println(Arrays.toString(Direction.values()));
        
        tellDirection(Direction.EAST);
        tellDirection(Direction.NORTH);
        
        //adding get method to return client attribute. 
        System.out.println(""+Direction.EAST.getDegree());
        
        //how to traverse Enum members by a loop
        for(Direction direction: Direction.values()){
            System.out.println(direction.name() + " " +direction.getDegree());
        }
        //overriding toString() to print out enum member properties.
        System.out.println(" "+ Arrays.toString(Direction.values()));
                
        
    }

    public static void tellDirection(Direction direction) {
        //Enum value can be inferred without using identifier. 
        switch (direction) {
            case EAST:
                System.out.println("Goto East.");
                break;
            case SOUTH:
                System.out.println("Goto South");
                break;
            case WEST:
                System.out.println("Goto West");
                break;
            case NORTH:
                System.out.println("Goto North");
                break;
            default:
                System.out.println("Goto no where");

        }

    }
}


Thursday, 8 September 2016

Time Complexity

Time complexity is a  way to evaluate different algorithm performance. This is a relative method, which evaluates the order of input numbers ref. to the steps to be consumed. So the best performance is independent of input numbers, i.e, n power of zero;  The worst case, the performance is a result of n square. 

Types of Time Complexity: 
the worst case, the best case, and average case. 

Assumption: 
We have infinite memory. 
No matter what kind of operations, we assume it takes one unit of time. 

List implementations:
                      get  add  contains next remove(0) iterator.remove
ArrayList             O(1) O(1) O(n)     O(1) O(n)      O(n)
LinkedList            O(n) O(1) O(n)     O(1) O(1)      O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n)     O(1) O(n)      O(n)
Set implementations:
                      add      contains next     notes
HashSet               O(1)     O(1)     O(h/n)   h is the table capacity
LinkedHashSet         O(1)     O(1)     O(1) 
CopyOnWriteArraySet   O(n)     O(n)     O(1) 
EnumSet               O(1)     O(1)     O(1) 
TreeSet               O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)
Map implementations:
                      get      containsKey next     Notes
HashMap               O(1)     O(1)        O(h/n)   h is the table capacity
LinkedHashMap         O(1)     O(1)        O(1) 
IdentityHashMap       O(1)     O(1)        O(h/n)   h is the table 
EnumMap               O(1)     O(1)        O(1) 
TreeMap               O(log n) O(log n)    O(log n) 
ConcurrentHashMap     O(1)     O(1)        O(h/n)   h is the table 
ConcurrentSkipListMap O(log n) O(log n)    O(1)
Queue implementations:
                      offer    peek poll     size
PriorityQueue         O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1)     O(1) O(1)     O(n)
ArrayBlockingQueue    O(1)     O(1) O(1)     O(1)
LinkedBlockingQueue   O(1)     O(1) O(1)     O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue            O(log n) O(1) O(log n) O(1)
LinkedList            O(1)     O(1) O(1)     O(1)
ArrayDeque            O(1)     O(1) O(1)     O(1)
LinkedBlockingDeque   O(1)     O(1) O(1)     O(1)

Wednesday, 7 September 2016

SpringBoot Unserstanding

It is a wonderful framework.

Spring boot is not a new version spring framework, but a cover layer residing on the spring framework techniques. Before it, although Spring can do a lot for developers, it requires a lot.

The purpose of boot is to release developer from doing trivial, for instance, a lot of XML, annotation configurations and dependency setups. Thus, developers may focus on implementing Java code and business logic.

Developer focus on coding functionalities rather than configuring spring framework. SpringBoot auto-configuration may consider what dependencies in the classpath, via which to infer what needs to be configured. It is very impressive as developing with SpringBoot for it added two ways of development automation, i.e. starter dependencies and automatic configurations.  Consequently, it is pretty fast to build up a web application now.

Instead of auto-configuration, what if you want to configure SpringBoot differently? SpringBoot allows overriding auto-configuration as needed to achieve the goals of your applications.


Conditional loading:

  • @ConditionalOnClass
  • @ConditionalOnBean
  • @COnditonalOnProperty
  • @ConditonalOnMissingBean

 Properties based: 

Properties are also a big part of the default configuration for Spring Boot. 

  • Preconfigured "default" properties for AutoConfiguration classes. 
  • @EnableConfigurationProperties specifies the default property set.
  • Properties can always be  overridden

Additional conditionals:

Application type based
Resource (or file) based 
Expression based


Configuring Spring boot

Property-based configurations:  it is the common way
applcation.properties and application.yml

  • Environment variables. (runtime environment) 
  • Command-line injections
  • Cloud configurations(config server,valut,consul) 

Bean configuration: 

  • Adding beans to the default application class??
  • Adding beans to separate configuration classes.
  • Importing XML-based configurations.
  • Component scanning





Tuesday, 6 September 2016

Arrays.asList returns an unmodified array list


Arrays.asList returns an un-modified ArrayList instance, i.e. read only .
        List list = Arrays.asList(12,10,129);
        list.add(15);
It throws a runtime exception, java.lang.UnsupportedOperationException

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...