Commit dd484e46 by Patryk Czarnik

Program pokazujący referencje między obiektami i eksperytmenty LAZY / EAGER

parent 3936da00
package hr.model;
/** Wspólna nadklasa dla wszystkich klas encji w tym pakiecie. Miejsce na dodatkowe metody. */
import java.lang.reflect.Field;
import java.util.Collection;
/** Wspólna nadklasa dla wszystkich klas encji w tym pakiecie.
* Miejsce na dodatkowe metody.
* Wykorzystuję je na zdefiniowanie "uniwersalnego toString" za pomocą mechanizmów refleksji.
* Mały problem: wypisanie obiektu powoduje wymuszenie załadowania wszyskich jego pól,
* nawet jeśli są "LAZY" z punktu widzenia Hibernate.
* Dla kolekcji dodałem specjalnego ifa, który nie powoduje wejścia do wnętrza kolekcji.
*/
abstract class AbstractEntity {
public String hello() {
return "hello";
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
Class<? extends AbstractEntity> klasa = this.getClass();
result.append(klasa.getSimpleName()).append(" [");
int fieldNo = 0;
for(Field field : klasa.getDeclaredFields())
try {
if(fieldNo++ > 0) {
result.append(", ");
}
Object value = "";
if(Collection.class.isAssignableFrom(field.getType())) {
value = "[]";
} else if(field.trySetAccessible()) {
value = field.get(this);
} else {
value = "!";
}
result.append(field.getName()).append('=').append(value);
} catch (IllegalArgumentException | IllegalAccessException e) {
System.err.println(e);
}
result.append("]");
return result.toString();
}
}
......@@ -12,7 +12,7 @@ public class Country extends AbstractEntity {
@Column(name = "country_name", length = 40)
private String countryName;
@ManyToOne(fetch = FetchType.LAZY)
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "region_id")
private hr.model.Region region;
......
......@@ -21,7 +21,7 @@ public class Department extends AbstractEntity {
@Column(name = "manager_id")
private Integer managerId;
@ManyToOne(fetch = FetchType.LAZY)
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "location_id")
private hr.model.Location location;
......
......@@ -29,7 +29,7 @@ public class Employee extends AbstractEntity {
@Column(name = "hire_date", nullable = false)
private LocalDate hireDate;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@ManyToOne(optional = false)
@JoinColumn(name = "job_id", nullable = false)
private hr.model.Job job;
......
......@@ -24,7 +24,7 @@ public class Location extends AbstractEntity {
@Column(name = "state_province", length = 25)
private String stateProvince;
@ManyToOne(fetch = FetchType.LAZY)
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "country_id")
private Country country;
......
......@@ -4,6 +4,7 @@ import hr.model.Country;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import org.hibernate.Session;
public class P0_OdczytajKraj {
public static void main(String[] args) {
......@@ -12,12 +13,20 @@ public class P0_OdczytajKraj {
System.out.println("Jest fabryka: " + emf);
EntityManager em = emf.createEntityManager();
System.out.println("Jest EM: " + em);
System.out.println("Jest EM: " + em + " , klasa: " + em.getClass().getName());
Country country = em.find(Country.class, "UK");
System.out.println(country);
System.out.println("Kod kraju: " + country.getCountryId() + ", nazwa: " + country.getCountryName());
// Gdy naszą implementacją jest Hibernate,
// obiekt EntityManager jest implementowany jako obiekt org.hibernate.Session
// Gdyby tej wersji użyć - to będziemy mieli do dyspozycji więcej metod.
Session session = em.unwrap(Session.class);
// Session session = (Session)em;
Country country2 = session.byId(Country.class).load("US");
System.out.println("Kod kraju: " + country2.getCountryId() + ", nazwa: " + country2.getCountryName());
System.out.println("Zamykamy...");
em.close();
emf.close();
......
package przyklady;
import hr.model.*;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import java.util.Scanner;
public class P1_OdczytajPracownika {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try(EntityManagerFactory emf = Persistence.createEntityManagerFactory("hr");
EntityManager em = emf.createEntityManager()) {
while(true) {
System.out.print("Podaj id pracownika: ");
int id = sc.nextInt();
if(id < 0) break;
Employee employee = em.find(Employee.class, id);
System.out.println(employee);
// w przypadku braku takiego obiektu wynikiem jest null
if(employee != null) {
System.out.println(employee.getFirstName()
+ " " + employee.getLastName() + " zarabia " + employee.getSalary());
Job job = employee.getJob();
System.out.println("Job: " + job + " " + job.getJobId() + " = " + job.getJobTitle());
Department dep = employee.getDepartment();
if(dep != null) {
System.out.println("a kuku");
System.out.println("Klasa obiektu Department: " + dep.getClass().getName());
// w przypadku zależności LAZY, dopiero teraz zostaną wczytane szczegóły departamentu
System.out.println("Department: " + dep.getDepartmentName());
System.out.println("Adres: " + dep.getLocation().getStreetAddress()
+ " " + dep.getLocation().getCity()
+ " " + dep.getLocation().getCountry().getCountryName());
}
}
}
}
}
}
......@@ -15,6 +15,18 @@
<property name="jakarta.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/hr"/>
<property name="jakarta.persistence.jdbc.user" value="alx"/>
<property name="jakarta.persistence.jdbc.password" value="abc123"/>
<!--
<property name="jakarta.persistence.jdbc.url" value="jdbc:postgresql://vps-2bc225bd.vps.ovh.net:5432/hr"/>
<property name="jakarta.persistence.jdbc.user" value="alx"/>
<property name="jakarta.persistence.jdbc.password" value="abc123vps"/>
-->
<!-- własności, które często się definiuje, ale jak widać bez nich też działa: -->
<property name="jakarta.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<!-- wypisywanie wszystkich poleceń SQL, które wykonuje Hibernate -->
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment