-1

How can I store an object (entity) in memory to get it later only in a working application with Hibernate?

@Entity
@Table(name = "users") 
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id; 

    @Column(name = "name") 
    private String name;

    @Column(name = "password")
    private String password;

    //without save this to database but in memory
    private boolean drunk;
}

How to get an object from memory with variable "drunk"?

I'm using now this to get object:

session.createQuery("SELECT u FROM User u WHERE u.name LIKE :name")
                .setParameter("name", name)
                .getResultList();
Dr. Bright
  • 19
  • 7

1 Answers1

0

You can user @Transient annotation, It indicates that a field is not to be persisted in the database.

import javax.persistence.Transient;

@Entity
@Table(name = "users") 
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id; 

    @Column(name = "name") 
    private String name;

    @Column(name = "password")
    private String password;

    //without save this to database but in memory
    @Transient
    private boolean drunk;
}

However you would need to define how this value would be set after you read it again from database later.

Cristian Colorado
  • 2,022
  • 3
  • 19
  • 24
  • But how save this object with field to get it later? – Dr. Bright Mar 03 '19 at 20:06
  • So, do you want to save the object somewhere outside database to access it later? – Cristian Colorado Mar 03 '19 at 20:08
  • No, only in memory. For example user is "drunk" (is not needed to save to database) – Dr. Bright Mar 03 '19 at 20:12
  • Ok, i think you need to take a look at session object, usually for authentication scenario we use it to save user data while user is going thru application. Here is an example of how to use it https://stackoverflow.com/questions/33481815/how-to-store-retrieved-object-in-session-and-access-it-afterwords – Cristian Colorado Mar 03 '19 at 20:13