tutorials

Showing posts with label tutorials. Show all posts
Showing posts with label tutorials. Show all posts

The best way to map @OneToOne


@OneToOne

The best approach to bidirectional @OneToOne is to use @MapsId

Student entity

@Entity
@Data
@Table(name = "students")
public class Student implements Serializable {

    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private String email;

    @OneToOne(mappedBy = "student", cascade = CascadeType.ALL)
    private StudentDetails studentDetails;
}

StudentDetails entity

@Entity
@Data
@Table(name = "student_details")
public class StudentDetails implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String studentDetailsInfo;

    @OneToOne
    @JoinColumn(name = "student_id")
    @MapsId
    private Student student;
}

The best way to map @ManyToMany


@ManyToMany

Many to many relationships can be easily mapped by creating another table using @JoinTable as follows.

Student entity

@Data
@Table(name = "Student")
@Entity
public class Student implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String studentName;

    @ManyToMany
    @JoinTable(
        name = "student_task",
        joinColumns = @JoinColumn(name = "task_id"),
        inverseJoinColumns = @JoinColumn(name = "student_id")
    )
    private Set<Task> tasks = new HashSet<>();
}


Task entity

@Entity
@Data
@Table(name = "tasks")
public class Task implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String taskName;

    @ManyToMany(mappedBy = "tasks")
    private Set<Student> students = new HashSet<>();
}

How to avoid NullPointerException


java.lang.NullPointerException

When can it be thrown?

According to the JavaDoc, the following scenarios can be found.
  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

How to avoid it?

  • Use Optional in Java 8
  • Call equals() and equalsIgnoreCase() methods on known objects.
  • Use valueOf() over toString()
public class NullCheckDemo {
   public static void main(String args[]){
       Integer i = null;
       System.out.println(i.toString());      //This throws NullPointerException
       System.out.println(String.valueOf(i)); //This returns null
   }
}
  • Use null-safe methods and libraries. Ex: Apache Commons StringUtils.
  • Use @NotNull and @Nullable annotations
  • Always check for nulls.
public class NullDemo {
    public static void main(String args[]){
        Integer i = null;

        if(i != null)
            System.out.println(i);
        else
            System.out.println("error occurred");
    }
}


States of an object in Hibernate


Hibernate object states

There are three states
  • Transient 
    • If the object just created, no primary key and not associate with a session, then the object is in the transient state
  • Persistent 
    • If a session is open, the object is in the persistent state
  • Detached 
    • If a session is closed, the object is in the detached state

Streams vs Collections in Java


 Streams vs Collections


Collections
Streams
The collections are used to store & group data in data structures like List, Set, Map...etc.Streams are used to perform complex operations like filtering, matching, mapping, etc... on stored data
Data modification can be done. You can add or remove data from a CollectionData cannot be modified
External iterations need to be done Internal iterations are being used
Collections can be traversedStreams can be traversed only once. If you need another traverse, you need to create a new stream
Collections are eagerly constructedStreams are lazily constructed




Bean scopes in Spring Framework


Spring Bean scopes

Set up the scope

  • The @Scope annotation can be used
@Scope("singleton")
  • There are 6 scopes are available in the application context

singleton

  • This is the default scope.
  • The same object is returned every time.
  • Better to use for all stateless beans.

prototype

  • A new object is created every time.
  • Better to use for all stateful beans.

request

  • Here it will create a single instance and it will available in the complete lifecycle of an HTTP request
  • Only valid in ApplicationContext

session

  • Here it will create a single instance and it will available in the complete lifecycle of an HTTP session
  • Only valid in ApplicationContext

application

  • Here it will create a single instance and it will available in the complete lifecycle of the servlet context
  • Only valid in ApplicationContext

websocket

  • Here it will create a single instance and it will available in the complete lifecycle of the web socket
  • Only valid in ApplicationContext

Dependency injection in Spring Boot


Dependency injection


What is Dependency injection?

  • Dependency injection is a form of the IoC container
  • It is just passing dependencies to other objects or frameworks.
  • Dependency injection allows you to remove hardcoded dependencies and make applications loosely coupled, extendable and maintainable.
  • In Spring it uses two types of dependency injection methods, constructor and setter injection. In addition, we can use field injection as well.

Constructor injection

private final Flavor flavor;

Cake(Flavor flavor) {
    Objects.requireNonNull(flavor);
    this.flavor = flavor;
}
  • If there is a single construction, @Autowired annotation is optional after Spring 4.3. But if there is more than one constructor, we need to specify the constructor by mentioning it using @Autowired annotation.
  • Autowired field should be final
  • This method is immutable and reliable

Setter injection

private Topping toppings;

@Autowired
void setTopping(Topping toppings) {
    this.toppings = toppings;
}
  • More flexible
  • Objects are mutable
  • Null checks are required
  • Less secure than constructor injection, because dependencies can be overridden

Field injection

@Autowired
private Topping toppings;

  • Very easy to use, but not recommended. 
  • If you use this, the unit tests can be failed.

When to use Setter or Constructor injections

  • Constructor injection is better than Setter injection.
  • Use Setter injection when a number of dependencies are more or you need readability.
  • Use Constructor Injection when Object must be created with all of its dependencies.
  • We can change a value easily when using the setter injection. It is more flexible than constructor injection.
  • Setter injection will override the constructor injection. If we use both setter and constructor injection, the IOC container will use setter injection.

Why does constructor injection better than others?

  • All required dependencies are available at the initialization time.
  • This is very important in writing unit tests. Because it forces to load all objects for all dependencies.

Advantages of dependency injection

  • Easy unit testing
  • Configurable components
  • Separations of concerns
  • More control 

jar vs war in Spring Boot


 Use jar not war

  • If you run mvn clean install in Spring Boot, you will get a fat jar file.
  • It contains everything like dependencies, embedded web server... etc.
  • You can just run java -jar jarFile in a JVM, the default is Tomcat embedded server or you can use Jetty.
  • You don't need any web server or application server to run spring boot jars.
  • Because spring boot will provide us a production-ready jar file with the embedded tomcat.
  • If you need to run spring boot applications in existing web servers, you may have to create war instead of a jar.
  • Spring Boot supports only Tomcat, Jetty, and Undertow as the embedded server