Close

JPA - @NamedEntityGraph Examples

JPA JAVA EE 

package com.logicbig.example;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
@NamedEntityGraph(name = "graph.module.projects.contractors",
attributeNodes = @NamedAttributeNode(value = "projects", subgraph = "projects.contractors"),
subgraphs = @NamedSubgraph(name = "projects.contractors",
attributeNodes = @NamedAttributeNode(value = "contractors")))
public class TradingModule {
@Id
@GeneratedValue
private int id;
private String name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Project> projects;

public int getId() {
return id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Set<Project> getProjects() {
return projects;
}

public void addProject(Project project) {
if (projects == null) {
projects = new HashSet<>();
}
projects.add(project);
}
}
Original Post




package com.logicbig.example;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;


@Entity
@NamedEntityGraph(name = "user-phones-entity-graph", attributeNodes = @NamedAttributeNode("phones"))
public class User {
@Id
@GeneratedValue
private int id;
private String name;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Set<Address> addresses;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Phone> phones;

public int getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Set<Address> getAddresses() {
return addresses;
}

public void setAddresses(Set<Address> addresses) {
this.addresses = addresses;
}

public Set<Phone> getPhones() {
return phones;
}

public void setPhones(Set<Phone> phones) {
this.phones = phones;
}

public void addPhone(String number, String type) {
if (phones == null) {
phones = new HashSet<>();
}
Phone p = new Phone();
p.setNumber(number);
p.setType(type);
phones.add(p);
}

public void addAddress(String street, String city, String country) {
if (addresses == null) {
addresses = new HashSet<>();
}
Address a = new Address();
a.setStreet(street);
a.setCity(city);
a.setCountry(country);
addresses.add(a);
}
}
Original Post




See Also