Java session clear all

Java Guides

In this short article, we will learn how to remove cache objects from the first-level cache using the Session.clear() method with an example.

Session.clear() Method

This method is used to completely clear the session. Evict all loaded instances and cancel all pending saves, updates, and deletions. Do not close open iterators or instances of ScrollableResults.

Hibernate Session.clear() Method Example

package net.javaguides.hibernate.tutorial; import org.hibernate.Session; import org.hibernate.Transaction; import net.javaguides.hibernate.tutorial.config.HibernateJavaConfig; import net.javaguides.hibernate.tutorial.entity.Student; public class RemoveFirstCacheDemo < public static void main(String[] args) < Transaction transaction = null; try (Session session = HibernateJavaConfig.getSessionfactory().openSession()) < // start the transaction transaction = session.beginTransaction(); // get the student entity using id Student student1 = session.load(Student.class, new Long(1)); System.out.println(student1.getFirstName()); System.out.println(student1.getLastName()); System.out.println(student1.getEmail()); // load student entity by id Student student2 = session.load(Student.class, new Long(1)); System.out.println(student2.getFirstName()); System.out.println(student2.getLastName()); System.out.println(student2.getEmail()); session.clear(); // load student entity by id Student student3 = session.load(Student.class, new Long(1)); System.out.println(student3.getFirstName()); System.out.println(student3.getLastName()); System.out.println(student3.getEmail()); // commit transaction transaction.commit(); > catch (Exception e) < if (transaction != null) < transaction.rollback(); > > > >
Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=? Prabhas Fadatare prabhas@gmail.com Prabhas Fadatare prabhas@gmail.com Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=? Prabhas Fadatare prabhas@gmail.com 

Clearly, a clear() method removed all the student objects from the first-level cache so that it was fetched again from the database.

Читайте также:  Защита своего php скрипта

Источник

IT Experts

Hibernate

Clear () : When this method get called inside transaction boundry then all objects which are currently associate with particular session will be disconnected / clean or no longer associate with that Session instance.

Therefore, after calling this method nothing will be performed on persistance layer or DB.

evict(): Removes the object from the session. This method is used to dissociate/disconnect the specified object from the session.

Close() : Close session by calling session.close() method, means End the session and releasing the JDBC Connection and clean up.

Below, we demonstrated using examples through it would be easier to grab the terms difference.

Student.java :- This is a JPA Entity class.

package com.itexperts.hibernate.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "Student") public class Student < @Id @GeneratedValue private long id; @Column(name = "NAME") private String name; @Column(name = "ENROLL_NO") private String rollno; @Column(name = "EMAIL") private String email; @Column(name = "created_date") @Temporal(TemporalType.DATE) private Date enrollmentDate; public Student() < >public Student(String name, String rollno, String email) < super(); this.name = name; this.rollno = rollno; this.email = email; this.enrollmentDate = new Date(); >public long getId() < return id; >public void setId(long id) < this.id = id; >public String getName() < return name; >public void setName(String name) < this.name = name; >public String getRollno() < return rollno; >public void setRollno(String rollno) < this.rollno = rollno; >public String getEmail() < return email; >public void setEmail(String email) < this.email = email; >public Date getEnrollmentDate() < return enrollmentDate; >public void setEnrollmentDate(Date enrollmentDate) < this.enrollmentDate = enrollmentDate; >>

Hibernate Configuration File under resource folder:-

Note: Here we set Hibernate config property( hbm2ddl.auto ) is create which means every time when program get executed, Hibernate automatically drop scheme and recreate Entity Table.

     jdbc:mysql://localhost:3306/mydb root root com.mysql.jdbc.Driver org.hibernate.dialect.MySQLDialect true true --> create 1 thread     

In this below example, we will see how session.clear() work and it’s implementation.

HibernateTest1.java:- Here we have two sessions, one for saving persistant object and right after open another session to get Object from DB using get().

package com.itexperts.relationship.example; import org.hibernate.Session; import org.hibernate.Transaction; import com.itexperts.hibernate.model.Student; import com.itexperts.utils.HibernateUtils; public class HibernateTest1 < public static void main(String[] args) < // 3 Student Objects Initialized here. Student student0 = new Student("Student1", "Student1-234","Student1@domain.com"); Student student1 = new Student("Student1", "Student1-234","Student1@domain.com"); Student student2 = new Student("Student1", "Student1-234","Student1@domain.com"); // This Transaction boundry, Transist Objects get persisted. // Start Session 1 Session session = HibernateUtils.getInstance().openSession(); Transaction tx = session.beginTransaction(); session.save(student0); session.save(student2); session.save(student1); tx.commit(); session.close(); // End Session1 // Again after saving Student Objects, poll up these object in another Transaction scope. session = HibernateUtils.getInstance().openSession(); tx = session.beginTransaction(); Student get_Student1 = (Student) session.get(Student.class, 1L); get_Student1.setName("Updated Student1"); // Completely clear the session. Evict all loaded instances and cancel all pending saves, updates and deletions. // after this Statement, None of operation will be performed on DB. session.clear(); // nothing reflected on Student1 instance in DB. tx.commit(); session.close(); > >

Generated Output here: here no any update SQL command fired.

Hibernate: drop table if exists Student
Hibernate: c reate table Student (id bigint not null auto_increment, EMAIL varchar(255), created_date date, NAME varchar(255), ENROLL_NO varchar(255), primary key (id))
Hibernate : insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate : insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate : insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate : select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?

Next, We will see how session.evit(object) work and it’s Implementation:-

Remove this instance from the session cache. Changes to the instance will not be synchronized with the database. This operation cascades to associated instances if the association is mapped with cascade="evict".

package com.itexperts.relationship.example; import org.hibernate.Session; import org.hibernate.Transaction; import com.itexperts.hibernate.model.Student; import com.itexperts.utils.HibernateUtils; public class HibernateTest1 < public static void main(String[] args) < // 3 Student Objects Initialized here. Student student0 = new Student("Student1", "Student1-234","Student1@domain.com"); Student student1 = new Student("Student1", "Student1-234","Student1@domain.com"); Student student2 = new Student("Student1", "Student1-234","Student1@domain.com"); // This Session boundry, Transist Object get persisted. // Start Session 1 Session session = HibernateUtils.getInstance().openSession(); Transaction tx = session.beginTransaction(); session.save(student0); session.save(student2); session.save(student1); tx.commit(); session.close(); // Again after saving Student Object, poll up these object again. session = HibernateUtils.getInstance().openSession(); tx = session.beginTransaction(); Student get_Student1 = (Student) session.get(Student.class, 1L); Student get_Student2 = (Student) session.get(Student.class, 2L); get_Student1.setName("Updated Student1"); get_Student1.setName("Updated Student2"); // Remove this instance from the session cache. Changes to the instance // will not be synchronized with the database. This operation cascades // to associated instances if the association is mapped with // cascade="evict". session.evict(get_Student2); // get_Student2 Object no more exists in Session therefore updation will not happened get_Student1 = (Student) session.get(Student.class, 1L); get_Student2 = (Student) session.get(Student.class, 2L); // Again we check out updatation get reflected or not.. System.out.println(" Student1 Name :"+get_Student1.getName()); System.out.println(" Student2 Name :"+get_Student2.getName()); tx.commit(); session.close(); > >

Generated Output:- here only one update command is issued by Hibernate subsequently only one Object get reflected in Database. In below output, you can see only student1’s name value get reflected while student2’s name remain same.

Hibernate: drop table if exists Student
Hibernate : create table Student (id bigint not null auto_increment, EMAIL varchar(255), created_date date, NAME varchar(255), ENROLL_NO varchar(255), primary key (id))
Hibernate : insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate : insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate : insert into Student (EMAIL, created_date, NAME, ENROLL_NO) values (?, ?, ?, ?)
Hibernate : select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?
Hibernate : select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?
Hibernate : select student0_.id as id0_0_, student0_.EMAIL as EMAIL0_0_, student0_.created_date as created3_0_0_, student0_.NAME as NAME0_0_, student0_.ENROLL_NO as ENROLL5_0_0_ from Student student0_ where student0_.id=?
Student1 Name :Updated Student2
Student2 Name :Student1
Hibernate: update Student set EMAIL=?, created_date=?, NAME=?, ENROLL_NO=? where >

And Finally, session.close()

close the session by calling session.close() after transaction is completed.All the associated objects will be dissociated after calling session.close().It is not strictly necessary to close the session but you must at least using disconnect it using session.disconnect()

Источник

Session use

1. When the browser first requests the server, the server generates a sessionID and returns to the browser, which will be saved in the browser’s session cookie.

2. In the case where the browser is not closed, each request request head will carry this sessionID to the server (generally setting the update server session time)

3. If the browser has been 30 minutes, then the second request is launched. At this time, the server session has been emptied, and the server will generate a new sessionID to the browser (with a new session existence server), replacing before SenseID of the browser

4, the third request, the new sessionid on the belt (SemsionID is saved in cookies, if the cookie is disabled, cookie can’t save the sessionid, but we can use the URL to override technology, put the sessionid as a parameter to the URL ).

By default, session is stored in the server for 30 minutes, saved some information for the user, once session clears, all the data of the user will be cleared. Then do we have to go back to log in? We need to re-login, just cookie helps us log in automatically, and the general server saves a cookie on our browser to verify the identity. Every time we will help us on, in fact, every time we open the browser, open a new URL. At this time, cookies will help us silently or so on, but we can’t feel it.

Therefore, we generally verify the user information (interceptor), generally see if the user saves the user object in Session, if not, get the account number and password in the cookie to see if you can log in, if you still don’t do it, go directly to login page;

About session storage problem

We know that session is the basic information of the server saves the user.

For individual servers, we can save the session to your local server.

For multiple servers, multiple servers share session, we must put the session in a public place (such as redis), or use JWT

Basic use process

Request login.html -> Store the required data into the session, or store subsequent repeatedly used data into the session

Request Home.html -> Get the session, remove the data we have stored in the session.

use: Create session objects / get session objects HttpSession HS = Req.getSession (); If the identifier of the session in the request is JSessionID, return its corresponding session object, If there is no session in the request is JsessionID, create a new session object and put it JSessionID as a browser from the cookie data. If the session object is invalid, you will also recreate a session object and store its JSessionID in the browser memory.

Session configuration

Set the session storage time (unit: second), default for 30 minutes, each request will reset the failure time hs.setMaxInactiveInterval(5); Get sessionid hs.getId(): Set session mandatory failure hs.invalidate();l Storing data hs.setAttribute("name",name); retrieve data hs.getAttribute("name") Using the timing: General users store the user's personal information to the SESION when logging in to the Web project, for the user's other requests.

Direct configuration session expiration time

1. Modify this time in the web.xml in Tomcat (under the Conf Directory)

import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; @WebServlet("/login") public class LoginServlet extends HttpServlet < @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException < Cookie[] cookies = req.getCookies(); for (Cookie cookie:cookies)< if ("username".equals(cookie.getName()))< String value = cookie.getValue(); / / Judgment if the user exists (check the database, verifying if the user exists) if ("admin".equals(value))< // Set the session, save the session HttpSession session = req.getSession(); session.setAttribute("username",value); resp.sendRedirect("/home"); return; >> > resp.sendRedirect("/login.jsp"); > @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException < String username = req.getParameter("username"); String pwd = req.getParameter("pwd"); // Query the database, if you have a user, set the session if (true)< // Set cookie, free landing Cookie cookie = new Cookie("username",username); cookie.setMaxAge(60*5); cookie.setPath("/"); resp.addCookie(cookie); // Set the session, save the session HttpSession session = req.getSession(); session.setAttribute("username",username); session.setAttribute("pwd",pwd); resp.sendRedirect("/home"); >> >
@WebServlet("/home") public class ServletDemo extends HttpServlet < @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException < HttpSession session = req.getSession(); Object username = session.getAttribute("username"); if(username==null)< resp.sendRedirect("/login"); return; >resp.setHeader("content-type","text/html;charset=utf-8"); Resp.getwriter (). Write (String) UserName + "Login Success"); > >

Источник

Оцените статью