basics

Showing posts with label basics. Show all posts
Showing posts with label basics. Show all posts

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");
    }
}


Throw vs throws in exception handling


Throw vs throws



Throw
Throws
Uses inside a method when it is required to throw an exceptionThis is used in the method signature in which methods that exceptions can occur. 
Only one exception can be thrownThrows can be used to declare multiple exceptions
Used to handle unchecked exceptionsUsed to handle checked exceptions
Usually used to handle custom exceptionsThrows means, it says this method can be thrown these exceptions, when you use this method, you need to handle it.