Sunday, July 23, 2017

Program of Linked List Insertion and Deletion Operations in java

Linkedlist as we all know is one of the most important topic of interview especially for coding round.

We will not talk more about the theoretical part of linked list

Program for the insertion and deletion operation of linkedlist.

public class LinkedList{
Node head;
Node current;
public static class Node{
int data;
Node next;
Node(int d){
data =d; next=null;
}
}
// insert at the fr=ont of the linkedlist
public void insertAtFirst(int d){
if(head ==null)
{
head = new Node(d);
// return true;
}
else{
Node n = new Node(d);
n.next =head;
head =n;
}
// return false;
}
public void insertAfter(int n1,int d){
Node temp =head;
while(temp!=null){
if(temp.data==n1){
Node n =new Node(d);
n.next =temp.next;
temp.next =n;
break;
}else{
temp=temp.next;
}
}
}
public void insert(int d){
if(head==null)
{
System.out.println("out");
head =new Node(d);
current =head;
// return true;
}else{
System.out.println("in ");
Node n = new Node(d);
current.next=n;
current=current.next;
// return true;
}
}
public void delete(int d){
Node currentNode=head;
Node previousNode=null;
if(head.data ==d){
head = head.next;
}else{
while(currentNode!=null){
if(currentNode.data==d){
previousNode.next=currentNode.next;
break;
}else{
previousNode=currentNode;
currentNode =currentNode.next;
}
}
}
}
public void show(){
System.out.println("---Showing---");
Node myNode =head;
while(myNode!=null){
System.out.println(myNode.data);
myNode =myNode.next;
}
}
// delete linkedlist at a given position
public void deleteAtPosition(int d){
Node temp =head;
Node prev =null;
int count=1;
if(d==1){
head =head.next;
}else{
while(temp!=null)
{
if(count==d){
prev.next=temp.next;
break;
}else{
prev =temp;
temp =temp.next;
count++;
}
}
}
}
}
view raw LinkedList.java hosted with ❤ by GitHub

In my earlier post I have talked about Tower of Hanoi problem 
You can also see other Sorting program
Bubble Sort 
Selection Sort
Insertion Sort 

Main Class File

class LinkedListOperations {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(1);
list.insert(2);
list.insert(4);
list.insert(3);
list.insert(5);
list.show();
list.delete(2);
list.delete(4);
list.show();
list.insertAtFirst(9);
list.show();
list.insertAfter(3,4);
list.show();
list.insertAfter(5,6);
list.show();
list.deleteAtPosition(3);
list.show();
list.deleteAtPosition(1);
list.show();
}
}



Hope this will help you in understand the program , Let me knowif you guys facing any problem in understanding this .


Thanks for reading.
-Noeik

Monday, July 3, 2017

Hibernate Mapping - OneToOne Relationship

Hello friend , Knowing one to one relation is very easy to understand for the interview aspirant , but to implement the knowledge into programming is the key which makes one a good programmer.

Today we will learn more about hibernate mapping -One to one

Breif- There are FOUR relationship mapping between object (tables)

  • ONE TO ONE
    • Unidirectional 
    • bidirectional
  • ONE TO MANY
    • Unidirectional 
    • bidirectional
  • MANY TO ONE
    • Unidirectional 
    • bidirectional
  • MANY TO MANY 
    • Unidirectional 
    • bidirectional

One to One mapping- In One to One mapping one object (row of a table ) is associated only with one another object(row of a table)

Ex - A user have only one System Credential.

When we say Uni directional - it means we dont have target to source mapping , we only have source to target mapping.
But in bidirectional we will have source to target to and fro mapping.

In Today's post we will see the ONE TO ONE UNIDIRECTION PROGRAM-

The Project Structure should be like below




package com.vp.learning.hibernate.data;
import java.util.Date;
import org.hibernate.Session;
import com.vp.learning.hibernate.data.entities.Credential;
import com.vp.learning.hibernate.data.entities.User;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Credential c = new Credential();
c.setUsername("programinjava");
c.setPassword("noeik");
User user = new User();
user.setBirthDate(new Date());
user.setCreatedBy("noeik");
user.setCreatedDate(new Date());
user.setEmailAddress("admin@noeik.com");
user.setFirstName("noeik");
user.setLastName("Noeik");
user.setLastUpdatedBy("Noeik");
user.setLastUpdatedDate(new Date());
c.setUser(user);
session.save(c);
session.getTransaction().commit();
session.close();
HibernateUtil.getSessionFactory().close();
}
}


package com.vp.learning.hibernate.data;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.vp.learning.hibernate.data.entities.Credential;
import com.vp.learning.hibernate.data.entities.User;
public class HibernateUtil {
private static final SessionFactory sessionFactory= buildSessionFactory();
private static SessionFactory buildSessionFactory(){
try{
Configuration config = new Configuration();
config.addAnnotatedClass(Credential.class);
config.addAnnotatedClass(User.class);
return config.buildSessionFactory(new StandardServiceRegistryBuilder().build());
}
catch(Exception e){
e.printStackTrace();
throw new RuntimeException("Some Exception occured");
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}


package com.vp.learning.hibernate.data.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name="credential")
public class Credential {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="CREDENTIAL_ID")
Long Id ;
@Column(name="USERNAME")
String username;
@Column(name="PASSWORD")
String password;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn( name="USER_ID" ,nullable=false)
private User user;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
view raw Credential.java hosted with ❤ by GitHub

package com.vp.learning.hibernate.data.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;
@Entity
@Table(name="finances_user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="USER_ID")
private String userId;
@Column(name="FIRST_NAME")
private String firstName;
@Column(name="LAST_NAME")
private String lastName;
@Column(name="BIRTH_DATE")
private Date birthDate;
@Column(name="EMAIL_ADDRESS")
private String emailAddress;
@Column(name="CREATED_DATE" ,updatable=false)
private Date createdDate;
@Column(name="CREATED_BY",updatable=false)
private String createdBy;
@Column(name="LAST_UPDATED_BY")
private String lastUpdatedBy;
@Column(name="LAST_UPDATED_DATE")
private Date lastUpdatedDate;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Date getLastUpdatedDate() {
return lastUpdatedDate;
}
public void setLastUpdatedDate(Date lastUpdatedDate) {
this.lastUpdatedDate = lastUpdatedDate;
}
}
view raw User.java hosted with ❤ by GitHub


hibernate.connection.username=root
hibernate.connection.password=root
hibernate.connection.url=jdbc:mysql://localhost:3306/learning
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\\mkyongapp.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger option
log4j.rootLogger=INFO, file, stdout
# Log everything. Good for troubleshooting
log4j.logger.org.hibernate=INFO
# Log all JDBC parameters
log4j.logger.org.hibernate.type=ALL

SQL Scripts
CREATE TABLE `finances_user` (
  `USER_ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `FIRST_NAME` varchar(45) NOT NULL,
  `LAST_NAME` varchar(45) NOT NULL,
  `BIRTH_DATE` date NOT NULL,
  `EMAIL_ADDRESS` varchar(100) NOT NULL,
  `LAST_UPDATED_BY` varchar(45) NOT NULL,
  `LAST_UPDATED_DATE` datetime NOT NULL,
  `CREATED_BY` varchar(45) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  `USER_ADDRESS_LINE_1` varchar(100) DEFAULT NULL,
  `USER_ADDRESS_LINE_2` varchar(100) DEFAULT NULL,
  `CITY` varchar(100) DEFAULT NULL,
  `STATE` varchar(2) DEFAULT NULL,
  `ZIP_CODE` varchar(5) DEFAULT NULL,
  PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;


CREATE TABLE `credential` (
  `CREDENTIAL_ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `USER_ID` bigint(20) NOT NULL,
  `USERNAME` varchar(50) NOT NULL,
  `PASSWORD` varchar(100) NOT NULL,
  PRIMARY KEY (`CREDENTIAL_ID`),
  UNIQUE KEY `USER_ID_UNIQUE` (`USER_ID`),
  CONSTRAINT `FINANCES_USER_FK` FOREIGN KEY (`USER_ID`) REFERENCES `finances_user` (`USER_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;


DOWNLOAD - SOURCE CODE (if deleted let us know)

Let us know if you dont understand anything in this post .

Thanks for reading 
-Noeik