Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Monday, October 18, 2021

Projection in hibernate

 Projection are used to execute aggregate operations and for single value query .

EX -

public static void main(String[] args) {
    SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class).buildSessionFactory();
    Session session = factory.getCurrentSession();
    try {
        session.beginTransaction();
        Criteria c = session.createCriteria(Student.class);
        Projection p = Projections.property("lastName");
        List<String> students = c.setProjection(p).list();
        for(String s:students)
            System.out.println(s);
        session.getTransaction().commit();
        session.close();
    } finally {
        factory.close();
    }
}
It will return values of last name column.
Projections are useful for 
1.Fetching only certain column of the table.
2.To execute aggregate function.

Sunday, June 6, 2021

Hibernate object life cycle state

Hibernate life cycle contains the following states: 

1.Transient

2.Persistent

3.Detached

1.Transient:The initial states of an object.when an object is created it entered into transient state.It is not associated with any session.So this state is not related to any db . In transient state object reside into heap memory.

Ex: Person person = new Person();//Here person is in transient state

person.setName("Lokman hossain");

2.Persistent:As soon as the object associated with the session ,it entered in the persistent state.Any modification in this state will effect the database .

ex:session.save(person);

session.persist(person);

session.saveOrUpdate(person);

session.merge(person);

session.lock(person);

3.Detached:When the session is closed the object entered into detached state.Changes will not effect the database.Object is no longer associated with hibernate session.

ex:session.close();

session.clear();

session.detach();

session.evict();


Tuesday, June 1, 2021

Hibernate one-To-many bi-directional:

 Hibernate one-To-many bi-directional:

Instructor class:

import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Instructor {
private int id;
private String first_name;
private String last_name;
private String email;

private List<Course> courses;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@OneToMany(mappedBy = "instructor",cascade  = CascadeType.ALL)
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}

//convenient method for bi-directional relationship.
public void add(Course tempCourse) {
if(courses==null) {
courses = new ArrayList<Course>();
}
courses.add(tempCourse);
tempCourse.setInstructor(this);
}
}

Course class:

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class Course {
private int id;
private String title;
private Instructor instructor;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}

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

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "instructor_id")
public Instructor getInstructor() {
return instructor;
}

public void setInstructor(Instructor instructor) {
this.instructor = instructor;
}

@Override
public String toString() {
return "Course [id=" + id + ", title=" + title + ", instructor=" + instructor + "]";
}
}

Main class:

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class MainApp {

public static void main(String[] args) {

SessionFactory sessionFactory = (SessionFactory) new Configuration().configure("Hibernate.cfg.xml")
.addAnnotatedClass(Instructor.class).addAnnotatedClass(Course.class).buildSessionFactory();

Session session = sessionFactory.getCurrentSession();
try {
Transaction tx = session.beginTransaction();

Instructor i1 = new Instructor();

i1.setFirst_name("nishat");
i1.setLast_name("nabila");
i1.setEmail("nabila@gmail.com");

Course c1 = new Course();
c1.setTitle("math");
c1.setInstructor(i1);

Course c2 = new Course();
c2.setTitle("physics");
c2.setInstructor(i1);

Course c3 = new Course();
c3.setTitle("social science");
c3.setInstructor(i1);

List<Course> allCourse = new ArrayList<Course>();
allCourse.add(c1);
allCourse.add(c2);
allCourse.add(c3);

i1.setCourses(allCourse);
session.save(i1);

tx.commit();

}

finally {
session.close();

}

}
}






Monday, May 31, 2021

Hibernate one-to-one mapping:

 Hibernate one-to-one mapping:

Person class:

@Entity

@Table(name="person")

public class Person {

private int personId;

private String name;

private PersonDetails personDetails;

@Id //used for primary key 

@GeneratedValue(strategy = GenerationType.IDENTITY) //mysql sequence generation policy

public int getPersonId() {

return personId;

}


public void setPersonId(int personId) {

this.personId = personId;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}

        //cascade type meaning what will happen for associated entity if this entity insert,delete ,update,merge or detach

//defining fetch type meaning if we fetch data then we want to fetch associated entity or not  

@OneToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)

@JoinColumn(name = "fk_id")

public PersonDetails getPersonDetails() {

return personDetails;

}

public void setPersonDetails(PersonDetails personDetails) {

this.personDetails = personDetails;

}

}

PersonDetails class:

@Entity

public class PersonDetails {

private int personDetailId;

private int income;

private String job;

private String zipCode;


@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

public int getPersonDetailId() {

return personDetailId;

}


public void setPersonDetailId(int personDetailId) {

this.personDetailId = personDetailId;

}


public int getIncome() {

return income;

}


public void setIncome(int income) {

this.income = income;

}


public String getJob() {

return job;

}


public void setJob(String job) {

this.job = job;

}


public String getZipCode() {

return zipCode;

}


public void setZipCode(String zipCode) {

this.zipCode = zipCode;

}


}

Main class:


public class MainApp {

public static void main(String[] args) {
SessionFactory sessionFactory = (SessionFactory) new Configuration().configure("Hibernate.cfg.xml")
.addAnnotatedClass(Person.class).addAnnotatedClass(PersonDetails.class).buildSessionFactory();

Session session = sessionFactory.getCurrentSession();
try {
Transaction tx = session.beginTransaction();
PersonDetails pdetails = new PersonDetails();
pdetails.setIncome(1000);
pdetails.setJob("engineer");
pdetails.setZipCode("1206");
Person p1 = new Person();
p1.setName("sahabur");
p1.setPersonDetails(pdetails);
session.save(p1);

tx.commit();
}

finally {
session.close();

}

}

}

hibernate.cfg.xml:

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/person_tracker?useSSL=false&amp;serverTimezone=UTC</property>
        <property name="connection.username">root</property>
        <property name="connection.password">lok094026man</property>

        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">5</property>

        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>

<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
 
    </session-factory>

</hibernate-configuration>




Testing controller

------Controller------------- @RestController @RequestMapping("/items") public class ItemController {     private final ItemServic...