13.4. Entity cache
`@Entity(name = "Phone") @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public static class Phone {
@Id @GeneratedValue private Long id;
private String mobile;
@ManyToOne private Person person;
@Version private int version;
public Phone() {}
public Phone(String mobile) { this.mobile = mobile; }
public Long getId() { return id; }
public String getMobile() { return mobile; }
public Person getPerson() { return person; }
public void setPerson(Person person) { this.person = person; } }`</pre> </div> </div> </div> </div>
Hibernate stores cached entities in a dehydrated form, which is similar to the database representation.
Aside from the foreign key column values of the @ManyToOne
or @OneToOne
child-side associations,
entity relationships are not stored in the cache,
</div>
Once an entity is stored in the second-level cache, you can avoid a database hit and load the entity from the cache alone:
</div>
`Person person = entityManager.find( Person.class, 1L );`</div> </div> </div> </div>
`Person person = session.get( Person.class, 1L );`</div> </div> </div> </div>
The Hibernate second-level cache can also load entities by their natural id:
</div>
`@Entity(name = "Person") @Cacheable @org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public static class Person {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id;
private String name;
@NaturalId @Column(name = "code", unique = true) private String code;
public Person() {}
public Person(String name) { this.name = name; }
public Long getId() { return id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCode() { return code; }
public void setCode(String code) { this.code = code; } }`</pre> </div> </div> </div> </div>
`Person person = session .byNaturalId( Person.class ) .using( "code", "unique-code") .load();`</div> </div> </div> </div> </div>