Commit 8b697af5 by Patryk Czarnik

Gotowe przykłady Hibernate / JPA

parent c105cf33
package hr.dto;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Objects;
public class AdressInfo {
private int employeeId;
private String firstName, lastName;
private String jobTitle;
private BigDecimal salary;
private LocalDate hireDate;
private String departmentName;
private String streetAddress;
private String postalCode;
private String city;
private String country;
public AdressInfo() {
}
public AdressInfo(int employeeId, String firstName, String lastName, String jobTitle, BigDecimal salary,
LocalDate hireDate, String departmentName, String streetAddress, String postalCode, String city,
String country) {
this.employeeId = employeeId;
this.firstName = firstName;
this.lastName = lastName;
this.jobTitle = jobTitle;
this.salary = salary;
this.hireDate = hireDate;
this.departmentName = departmentName;
this.streetAddress = streetAddress;
this.postalCode = postalCode;
this.city = city;
this.country = country;
}
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public LocalDate getHireDate() {
return hireDate;
}
public void setHireDate(LocalDate hireDate) {
this.hireDate = hireDate;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return "AdressInfo [employeeId=" + employeeId + ", firstName=" + firstName + ", lastName=" + lastName
+ ", jobTitle=" + jobTitle + ", salary=" + salary + ", hireDate=" + hireDate + ", departmentName="
+ departmentName + ", streetAddress=" + streetAddress + ", postalCode=" + postalCode + ", city=" + city
+ ", country=" + country + "]";
}
@Override
public int hashCode() {
return Objects.hash(city, country, departmentName, employeeId, firstName, hireDate, jobTitle, lastName,
postalCode, salary, streetAddress);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AdressInfo other = (AdressInfo) obj;
return Objects.equals(city, other.city) && Objects.equals(country, other.country)
&& Objects.equals(departmentName, other.departmentName) && employeeId == other.employeeId
&& Objects.equals(firstName, other.firstName) && Objects.equals(hireDate, other.hireDate)
&& Objects.equals(jobTitle, other.jobTitle) && Objects.equals(lastName, other.lastName)
&& Objects.equals(postalCode, other.postalCode) && Objects.equals(salary, other.salary)
&& Objects.equals(streetAddress, other.streetAddress);
}
}
package hr.dto;
import java.math.BigDecimal;
import java.util.Objects;
public class MiniEmp {
private String firstName, lastName;
private String jobTitle;
private BigDecimal salary;
public MiniEmp() {
}
public MiniEmp(String firstName, String lastName, String jobTitle, BigDecimal salary) {
this.firstName = firstName;
this.lastName = lastName;
this.jobTitle = jobTitle;
this.salary = salary;
//System.out.println("salary YES");
}
public MiniEmp(String firstName, String lastName, String jobTitle) {
this.firstName = firstName;
this.lastName = lastName;
this.jobTitle = jobTitle;
//System.out.println("salary NO");
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
@Override
public String toString() {
return "MiniEmp [firstName=" + firstName + ", lastName=" + lastName
+ ", jobTitle=" + jobTitle + ", salary=" + salary + "]";
}
@Override
public int hashCode() {
return Objects.hash(firstName, jobTitle, lastName, salary);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MiniEmp other = (MiniEmp) obj;
return Objects.equals(firstName, other.firstName)
&& Objects.equals(jobTitle, other.jobTitle) && Objects.equals(lastName, other.lastName)
&& Objects.equals(salary, other.salary);
}
}
package hr.dto;
import java.math.BigDecimal;
import java.util.Locale;
import java.util.Objects;
import jakarta.persistence.*;
@Entity
public class PracownikWDepartamencie {
@Id
private int id;
private String departmentName, firstName, lastName, jobTitle;
private BigDecimal salary, depAvg;
private int depPos, globalPos;
public PracownikWDepartamencie() {
}
public PracownikWDepartamencie(int id, String departmentName, String firstName, String lastName, String jobTitle,
BigDecimal salary, BigDecimal depAvg, int depPos, int globalPos) {
this.id = id;
this.departmentName = departmentName;
this.firstName = firstName;
this.lastName = lastName;
this.jobTitle = jobTitle;
this.salary = salary;
this.depAvg = depAvg;
this.depPos = depPos;
this.globalPos = globalPos;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public BigDecimal getDepAvg() {
return depAvg;
}
public void setDepAvg(BigDecimal depAvg) {
this.depAvg = depAvg;
}
public int getDepPos() {
return depPos;
}
public void setDepPos(int depPos) {
this.depPos = depPos;
}
public int getGlobalPos() {
return globalPos;
}
public void setGlobalPos(int globalPos) {
this.globalPos = globalPos;
}
@Override
public String toString() {
return "PracownikWDepartamencie [id=" + id + ", departmentName=" + departmentName + ", firstName=" + firstName
+ ", lastName=" + lastName + ", jobTitle=" + jobTitle + ", salary=" + salary + ", depAvg=" + depAvg
+ ", depPos=" + depPos + ", globalPos=" + globalPos + "]";
}
@Override
public int hashCode() {
return Objects.hash(depAvg, depPos, departmentName, firstName, globalPos, id, jobTitle, lastName, salary);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PracownikWDepartamencie other = (PracownikWDepartamencie) obj;
return Objects.equals(depAvg, other.depAvg) && depPos == other.depPos
&& Objects.equals(departmentName, other.departmentName) && Objects.equals(firstName, other.firstName)
&& globalPos == other.globalPos && id == other.id && Objects.equals(jobTitle, other.jobTitle)
&& Objects.equals(lastName, other.lastName) && Objects.equals(salary, other.salary);
}
public String dajInfo() {
return String.format(Locale.US, "%3d | %-12s %-12s %-33s | %8.2f | %-20s | %8.2f | %2d | %3d |",
id, firstName, lastName, "("+jobTitle+")", salary, departmentName, depAvg, depPos, globalPos);
}
public static String naglowek() {
return String.format(Locale.US, " id | pracownik | pensja | departament | średnia | nr | nr g|");
}
}
package hr.model;
import java.io.Serializable;
import jakarta.persistence.*;
/**
* The persistent class for the countries database table.
*
*/
@Entity
@Table(name="countries")
@NamedQuery(name="Country.findAll", query="SELECT c FROM Country c")
public class Country extends WspolnaNadklasa implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="country_id")
private String countryId;
@Column(name="country_name")
private String countryName;
//uni-directional many-to-one association to Region
@ManyToOne
@JoinColumn(name="region_id")
private Region region;
public Country() {
}
public String getCountryId() {
return this.countryId;
}
public void setCountryId(String countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return this.countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Region getRegion() {
return this.region;
}
public void setRegion(Region region) {
this.region = region;
}
}
\ No newline at end of file
package hr.model;
import java.io.Serializable;
import jakarta.persistence.*;
import java.util.List;
/**
* The persistent class for the departments database table.
*
*/
@Entity
@Table(name="departments")
@NamedQuery(name="Department.findAll", query="SELECT d FROM Department d")
public class Department extends WspolnaNadklasa implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="department_id", insertable=false, updatable=false)
private Integer departmentId;
@Column(name="department_name")
private String departmentName;
@Column(name="manager_id")
private Integer managerId;
//uni-directional many-to-one association to Location
@ManyToOne
@JoinColumn(name="location_id")
private Location location;
//bi-directional many-to-one association to Employee
@OneToMany(mappedBy="department")
private List<Employee> employees;
public Department() {
}
public Integer getDepartmentId() {
return this.departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return this.departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public Integer getManagerId() {
return this.managerId;
}
public void setManagerId(Integer managerId) {
this.managerId = managerId;
}
public Location getLocation() {
return this.location;
}
public void setLocation(Location location) {
this.location = location;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setDepartment(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setDepartment(null);
return employee;
}
}
\ No newline at end of file
package hr.model;
import java.io.Serializable;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
/**
* The persistent class for the employees database table.
*
*/
@Entity
@Table(name="employees")
@NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee extends WspolnaNadklasa implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="employee_id", insertable=false, updatable=false)
private Integer employeeId;
@Column(name="commission_pct")
private Double commissionPct;
private String email;
@Column(name="first_name")
private String firstName;
@Temporal(TemporalType.DATE)
@Column(name="hire_date")
private Date hireDate;
@Column(name="last_name")
private String lastName;
@Column(name="phone_number")
private String phoneNumber;
private BigDecimal salary;
//bi-directional many-to-one association to Department
@ManyToOne
@JoinColumn(name="department_id")
private Department department;
//uni-directional many-to-one association to Employee
// obiekt manager nie jest od razu wczytywany, tylko gdyby ktoś bezpośrednio pobrał za pomocą getManager()
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="manager_id")
private Employee manager;
//bi-directional many-to-one association to Job
@ManyToOne
@JoinColumn(name="job_id")
private Job job;
public Employee() {
}
public Integer getEmployeeId() {
return this.employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public Double getCommissionPct() {
return this.commissionPct;
}
public void setCommissionPct(Double commissionPct) {
this.commissionPct = commissionPct;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Date getHireDate() {
return this.hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public BigDecimal getSalary() {
return this.salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public Department getDepartment() {
return this.department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Employee getManager() {
return this.manager;
}
public void setManager(Employee manager) {
this.manager = manager;
}
public Job getJob() {
return this.job;
}
public void setJob(Job job) {
this.job = job;
}
}
\ No newline at end of file
package hr.model;
import java.io.Serializable;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.util.List;
/**
* The persistent class for the jobs database table.
*
*/
@Entity
@Table(name="jobs")
@NamedQuery(name="Job.findAll", query="SELECT j FROM Job j")
public class Job extends WspolnaNadklasa implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="job_id", updatable=false)
private String jobId;
@Column(name="job_title")
private String jobTitle;
@Column(name="max_salary")
private BigDecimal maxSalary;
@Column(name="min_salary")
private BigDecimal minSalary;
//bi-directional many-to-one association to Employee
@OneToMany(mappedBy="job")
private List<Employee> employees;
public Job() {
}
public String getJobId() {
return this.jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId;
}
public String getJobTitle() {
return this.jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public BigDecimal getMaxSalary() {
return this.maxSalary;
}
public void setMaxSalary(BigDecimal maxSalary) {
this.maxSalary = maxSalary;
}
public BigDecimal getMinSalary() {
return this.minSalary;
}
public void setMinSalary(BigDecimal minSalary) {
this.minSalary = minSalary;
}
public List<Employee> getEmployees() {
return this.employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Employee addEmployee(Employee employee) {
getEmployees().add(employee);
employee.setJob(this);
return employee;
}
public Employee removeEmployee(Employee employee) {
getEmployees().remove(employee);
employee.setJob(null);
return employee;
}
}
\ No newline at end of file
package hr.model;
import java.io.Serializable;
import jakarta.persistence.*;
/**
* The persistent class for the locations database table.
*
*/
@Entity
@Table(name="locations")
@NamedQuery(name="Location.findAll", query="SELECT l FROM Location l")
public class Location extends WspolnaNadklasa implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="location_id", insertable=false, updatable=false)
private Integer locationId;
private String city;
@Column(name="postal_code")
private String postalCode;
@Column(name="state_province")
private String stateProvince;
@Column(name="street_address")
private String streetAddress;
//uni-directional many-to-one association to Country
@ManyToOne
@JoinColumn(name="country_id")
private Country country;
public Location() {
}
public Integer getLocationId() {
return this.locationId;
}
public void setLocationId(Integer locationId) {
this.locationId = locationId;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostalCode() {
return this.postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getStateProvince() {
return this.stateProvince;
}
public void setStateProvince(String stateProvince) {
this.stateProvince = stateProvince;
}
public String getStreetAddress() {
return this.streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public Country getCountry() {
return this.country;
}
public void setCountry(Country country) {
this.country = country;
}
}
\ No newline at end of file
package hr.model;
import java.io.Serializable;
import jakarta.persistence.*;
/**
* The persistent class for the regions database table.
*
*/
@Entity
@Table(name="regions")
@NamedQuery(name="Region.findAll", query="SELECT r FROM Region r")
public class Region extends WspolnaNadklasa implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name="region_id", updatable=false)
private Integer regionId;
@Column(name="region_name")
private String regionName;
public Region() {
}
public Integer getRegionId() {
return this.regionId;
}
public void setRegionId(Integer regionId) {
this.regionId = regionId;
}
public String getRegionName() {
return this.regionName;
}
public void setRegionName(String regionName) {
this.regionName = regionName;
}
}
\ No newline at end of file
package hr.model;
import java.lang.reflect.Field;
abstract class WspolnaNadklasa {
@Override
public String toString() {
StringBuilder result = new StringBuilder();
Class<? extends WspolnaNadklasa> 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(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();
}
}
package hr.programy;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import hr.model.Employee;
public class Criteria1 {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hr_postgresql");
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = cb.createQuery(Employee.class); // typ wyniku
Root<Employee> root = cq.from(Employee.class); // tabela źródłowa
cq.select(root);
TypedQuery<Employee> query = em.createQuery(cq);
List<Employee> lista = query.getResultList();
System.out.println("Odczytano " + lista.size() + " rekordów.");
for (Employee emp : lista) {
System.out.printf("%-15s %-15s %8s %s\n", emp.getFirstName(), emp.getLastName(),
emp.getSalary(), emp.getJob().getJobTitle());
}
em.close();
emf.close();
}
}
package hr.programy;
import java.math.BigDecimal;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import hr.model.Employee;
public class Criteria2 {
public static void main(String[] args) {
BigDecimal minSalary = new BigDecimal(10000);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hr_postgresql");
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
// podajmey klasę dla wyników
CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
// podajemy encję / tabelę źródłową, od której zapytanie startuje
Root<Employee> root = cq.from(Employee.class);
// tak jakby dopisywanie kolejnych fragmentów zapytania
cq.select(root);
cq.where(cb.ge(root.get("salary"), minSalary));
cq.orderBy(cb.desc(root.get("salary")));
// Tutaj zastosowałem tworzenie kryteriów "dynamicznie" na podstawie nazw kolumn
// Istnieje też możliwość wygenerowanie "metamodelu" i posługiwania się nim
TypedQuery<Employee> query = em.createQuery(cq);
List<Employee> lista = query.getResultList();
System.out.println("Odczytano " + lista.size() + " rekordów.");
for (Employee emp : lista) {
System.out.printf("%-15s %-15s %8s %s\n", emp.getFirstName(), emp.getLastName(),
emp.getSalary(), emp.getJob().getJobTitle());
}
em.close();
emf.close();
}
}
package hr.programy;
import java.math.BigDecimal;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
import hr.model.Employee;
public class Criteria3 {
public static void main(String[] args) {
BigDecimal minSalary = new BigDecimal(4000);
String szukaneMiasto = "Seattle";
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hr_postgresql");
EntityManager em = emf.createEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);
Root<Employee> root = cq.from(Employee.class);
cq.select(root);
cq.where(cb.and(cb.ge(root.get("salary"), minSalary),
cb.equal(root.get("department").get("location").get("city"), szukaneMiasto)));
cq.orderBy(cb.desc(root.get("salary")));
TypedQuery<Employee> query = em.createQuery(cq);
List<Employee> lista = query.getResultList();
System.out.println("Odczytano " + lista.size() + " rekordów.");
for (Employee emp : lista) {
String miasto = emp.getDepartment() == null ? "-" : emp.getDepartment().getLocation().getCity();
System.out.printf("%-15s %-15s %-10s %8s %s\n", emp.getFirstName(), emp.getLastName(),
miasto, emp.getSalary(), emp.getJob().getJobTitle());
}
em.close();
emf.close();
}
}
package hr.programy;
import java.math.BigDecimal;
import java.math.RoundingMode;
import hr.model.Employee;
import sklep.model.Product;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
public class DwieBazyNaRaz {
public static void main(String[] args) {
try(EntityManagerFactory sklep_emf = Persistence.createEntityManagerFactory("sklep_pu");
EntityManagerFactory hr_emf = Persistence.createEntityManagerFactory("hr_postgresql");
EntityManager sklep_em = sklep_emf.createEntityManager();
EntityManager hr_em = hr_emf.createEntityManager()) {
System.out.println("Oba managery gotowe");
int employeeId = 100;
int productId = 1;
Employee employee = hr_em.find(Employee.class, employeeId);
Product product = sklep_em.find(Product.class, productId);
BigDecimal ilosc = employee.getSalary().divide(product.getPrice(), 1, RoundingMode.HALF_UP);
System.out.printf("Pracownik %s %s zarabia %s i może kupić %s sztuk produktu %s\n.",
employee.getFirstName(), employee.getLastName(), employee.getSalary(), ilosc, product.getProductName());
}
}
}
package hr.programy;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import hr.model.Employee;
public class Odczyt01_JedenRekord {
public static void main(String[] args) {
System.out.println("Początek");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hr_postgresql");
EntityManager em = emf.createEntityManager();
System.out.println("Udało się połączyć, em = " + em);
Employee emp = em.find(Employee.class, 100);
if(emp == null) {
System.out.println("nie znaleziono");
} else {
System.out.println(emp.getFirstName() + " " + emp.getLastName());
}
em.close();
emf.close();
}
}
package hr.programy;
import java.util.Scanner;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import hr.model.Department;
import hr.model.Employee;
public class Odczyt02_JedenRekord_InneTabele {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
System.out.println("Udało się połączyć, em = " + em);
while(true) {
System.out.print("Podaj id pracownika: ");
if(!sc.hasNextInt())
break;
int id = sc.nextInt();
Employee emp = em.find(Employee.class, id);
if(emp == null) {
System.out.println("nie znaleziono");
} else {
System.out.println(emp.getFirstName() + " " + emp.getLastName() + " $" + emp.getSalary());
System.out.println("job: " + emp.getJob().getJobTitle());
Department department = emp.getDepartment();
if (department != null) {
System.out.println("departament: " + department.getDepartmentName());
System.out.println("adres: " + department.getLocation().getStreetAddress() + " "
+ department.getLocation().getCity() + " "
+ department.getLocation().getCountry().getCountryName());
}
System.out.println();
}
}
} finally {
if(em != null)
em.close();
if(emf != null)
emf.close();
}
}
}
package hr.programy;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import hr.model.Employee;
public class Odczyt03_WszystkieRekordy_FindAll {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
TypedQuery<Employee> query = em.createNamedQuery("Employee.findAll", Employee.class);
// Wczytuje wszystkie dane od razu do pamięci
List<Employee> lista = query.getResultList();
System.out.println("Ilość rekordów " + lista.size());
for (Employee employee : lista) {
System.out.println(employee.getFirstName() + " " + employee.getLastName());
}
} finally {
if (em != null)
em.close();
if (emf != null)
emf.close();
}
}
}
package hr.programy;
import java.util.stream.Stream;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import hr.model.Employee;
public class Odczyt04_WszystkieRekordy_Stream {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
TypedQuery<Employee> query = em.createNamedQuery("Employee.findAll", Employee.class);
// Używając Stream zamiast List pobieramy dane "strumieniowo", czyli pojedynczo i przetwarzamy na bieżąco.
try(Stream<Employee> stream = query.getResultStream()) {
stream.forEach(emp -> {
System.out.println(emp.getFirstName() + " " + emp.getLastName());
});
}
} finally {
if (em != null)
em.close();
if (emf != null)
emf.close();
}
}
}
package hr.programy;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import hr.model.Employee;
public class Odczyt05_WszystkieRekordy_JPQL {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
TypedQuery<Employee> query = em.createQuery("SELECT emp FROM Employee emp", Employee.class);
List<Employee> lista = query.getResultList();
System.out.println("Ilość rekordów " + lista.size());
for (Employee employee : lista) {
System.out.println(employee.getFirstName() + " " + employee.getLastName());
}
} finally {
if (em != null)
em.close();
if (emf != null)
emf.close();
}
}
}
package hr.programy;
import java.util.List;
import javax.swing.JOptionPane;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import hr.model.Employee;
public class Odczyt06_Warunek {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
String kogoSzukam = JOptionPane.showInputDialog("Podaj kod stanowiska");
// to działało:
// TypedQuery<Employee> query = em.createQuery("SELECT emp FROM Employee emp WHERE job.jobId = ?1", Employee.class);
// query.setParameter(1, kogoSzukam);
// ale to już nie ("legacy parameter style"):
// TypedQuery<Employee> query = em.createQuery("SELECT emp FROM Employee emp WHERE job.jobId = ?", Employee.class);
// query.setParameter(1, kogoSzukam);
// wszystkie trzy zapisy zadziałały:
// TypedQuery<Employee> query = em.createQuery("SELECT emp FROM Employee emp WHERE job_id = :kto", Employee.class);
// TypedQuery<Employee> query = em.createQuery("SELECT emp FROM Employee emp WHERE job.jobId = :kto", Employee.class);
TypedQuery<Employee> query = em.createQuery("SELECT emp FROM Employee emp WHERE emp.job.jobId = :kto", Employee.class);
query.setParameter("kto", kogoSzukam);
List<Employee> lista = query.getResultList();
System.out.println("Ilość rekordów " + lista.size());
for (Employee employee : lista) {
System.out.println(employee.getFirstName() + " " + employee.getLastName());
//System.out.println(employee.getJob());
}
} finally {
if (em != null)
em.close();
if (emf != null)
emf.close();
}
}
}
package hr.programy;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
public class Odczyt07_Skalar {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
TypedQuery<String> query = em.createQuery("SELECT e.lastName FROM Employee e ORDER BY 1", String.class);
// też działa:
// TypedQuery<String> query = em.createQuery("SELECT lastName FROM Employee ORDER BY lastName", String.class);
List<String> names = query.getResultList();
for (String name : names) {
System.out.println(name);
}
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.Arrays;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
public class Odczyt08_Tablica {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
TypedQuery<Object[]> query = em.createQuery("SELECT e.firstName, e.lastName, e.job.jobTitle, e.salary, e.department.departmentName, e.department.location.city FROM Employee e", Object[].class);
List<Object[]> rows = query.getResultList();
for (Object[] emp : rows) {
System.out.println(Arrays.toString(emp));
}
System.out.println("\nSprawdzę typy kolumn:");
Object[] row = (Object[])rows.get(0);
System.out.println(row[0].getClass().getSimpleName() + " " + row[2].getClass().getSimpleName() + " " + row[3].getClass().getSimpleName());
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.List;
import hr.dto.MiniEmp;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
public class Odczyt09_DTO {
// Przykład zastosowania techniki (wzorca projektowego?...) DTO (data transfer object).
// Klasa DTO pełni rolę pomocniczą, nie stanowi głównego modelu aplikacji.
// Obiekty tej klasy służą przekazywaniu parametrów, zwracaniu wyników z metod,
// np. zbieraniu danych z formularza webowego lub - tak jak tutaj - zbieraniu wyników zapytania bazodanowego.
// Technicznie rzecz biorąc: w JPQL można użyć NEW aby stworzyć obiekt za pomocą konstruktora.
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
TypedQuery<MiniEmp> query = em.createQuery("SELECT new hr.dto.MiniEmp(e.firstName, e.lastName, e.job.jobTitle, e.salary) FROM Employee e", MiniEmp.class);
List<MiniEmp> emps = query.getResultList();
for (MiniEmp emp : emps) {
System.out.println(emp);
}
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.Arrays;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
public class Odczyt10_Group {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
TypedQuery<Object[]> query = em.createQuery("SELECT e.job.jobTitle, count(*), avg(e.salary) FROM Employee e GROUP BY e.job.jobTitle", Object[].class);
List<Object[]> emps = query.getResultList();
for (Object[] emp : emps) {
System.out.println(Arrays.toString(emp));
}
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.Arrays;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
public class Odczyt11_Join {
// Przykład JOIN zapisanego w składni JPQL - "przechodzenie po dowiązaniach".
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
System.out.println("Odczyt...");
TypedQuery<Object[]> query = em.createQuery("SELECT e.firstName, e.lastName, d.departmentName, l.city"
+ " FROM Employee e LEFT JOIN e.department d LEFT JOIN d.location l", Object[].class);
List<Object[]> emps = query.getResultList();
for (Object[] emp : emps) {
System.out.println(Arrays.toString(emp));
}
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import hr.model.Employee;
public class Odczyt12_WieleTabel {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
TypedQuery<Object[]> query = em.createQuery(
"SELECT DISTINCT emp, loc.city"
+ " FROM Employee emp, Location loc"
+ " WHERE substring(emp.lastName, 1, 1) = substring(loc.city, 1, 1)"
+ " ORDER BY emp.lastName, emp.firstName",
Object[].class);
List<Object[]> results = query.getResultList();
System.out.println(results.size());
for (Object[] tab : results) {
Employee emp = (Employee)tab[0];
String city = (String)tab[1];
System.out.printf("%-20s %-20s %-20s\n", emp.getFirstName(), emp.getLastName(), city);
}
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
// Prosty przykład native query.
// Wynik odczytywany jako lista wierszy, każdy wiersz jako Object[].
public class Odczyt13_Native {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
Query query = em.createNativeQuery(
"SELECT first_name || ' ' || last_name, job_title, salary FROM employees JOIN jobs USING(job_id) ORDER BY employee_id");
List<?> rows = query.getResultList();
for (Object row : rows) {
// na wszelki wypadek sprawdzam, ale widzę, że Object[] działa
if(row instanceof Object[]) {
Object[] cols = (Object[]) row;
System.out.println(cols[0] + " pracuje jako " + cols[1] + " i zarabia " + cols[2]);
}
}
System.out.println();
// Biorę pierwszy wiersz i (informacyjnie, dla nas podczas nauki) sprawdzam typy kolumn. Zauważmy, że kolumna salary jest mapowana na BigDecimal.
System.out.println("Sprawdzę typy kolumn:");
Object[] row = (Object[])rows.get(0);
System.out.println(row[0].getClass().getSimpleName() + " " + row[1].getClass().getSimpleName() + " " + row[2].getClass().getSimpleName());
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.Arrays;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
// Sensowny przykład native query.
// Pokazuję, że dzięki niemu można skorzystać z funkcji konkretnej bazy danych.
// Tutaj (z dokumentacją przed nosem ;) ) wykombinowałem zapytanie z "funkcjami okienkowymi"
// - funkcjonalność znana głównie w Oracle, dostępna także w PostgreSQL.
public class Odczyt14_Native {
public static void main(String[] args) {
final String sql = """
SELECT employee_id AS "id",
department_name AS "departmentName",
first_name AS "firstName",
last_name AS "lastName",
job_title AS "jobTitle",
salary AS "salary",
round(avg(salary) OVER (PARTITION BY department_id), 2) AS "depAvg",
round(salary - avg(salary) OVER (PARTITION BY department_id), 2) AS "diff",
rank() OVER (PARTITION BY department_id ORDER BY salary DESC) AS "depPos",
rank() OVER (ORDER BY salary DESC) AS "globalPos"
FROM departments d
INNER JOIN employees e USING(department_id)
INNER JOIN jobs j USING(job_id)
ORDER BY 7 DESC, 2, 6 DESC, 4 ASC, 3 ASC
""";
System.out.println(sql);
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
Query query = em.createNativeQuery(sql);
List<?> rows = query.getResultList();
for (Object row : rows) {
if (row instanceof Object[]) {
Object[] cols = (Object[]) row;
System.out.println(Arrays.toString(cols));
}
}
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.List;
import hr.dto.PracownikWDepartamencie;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
// Sensowny przykład native query.
// Pokazuję, że dzięki niemu można skorzystać z funkcji konkretnej bazy danych.
// Tutaj (z dokumentacją przed nosem ;) ) wykombinowałem zapytanie z "funkcjami okienkowymi"
// - funkcjonalność znana głównie w Oracle, dostępna także w PostgreSQL.
// W tej wersji dodatkowo wyniki pakuję do własnej klasy PracownikWDepartamencie
public class Odczyt15_Native_DTO {
public static void main(String[] args) {
final String sql = """
SELECT employee_id AS "id",
department_name AS "departmentName",
first_name AS "firstName",
last_name AS "lastName",
job_title AS "jobTitle",
salary AS "salary",
round(avg(salary) OVER (PARTITION BY department_id), 2) AS "depAvg",
rank() OVER (PARTITION BY department_id ORDER BY salary DESC) AS "depPos",
rank() OVER (ORDER BY salary DESC) AS "globalPos"
FROM departments d
INNER JOIN employees e USING(department_id)
INNER JOIN jobs j USING(job_id)
ORDER BY 7 DESC, 2, 6 DESC, 4 ASC, 3 ASC
""";
System.out.println(sql);
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
Query query = em.createNativeQuery(sql, PracownikWDepartamencie.class);
List<?> rows = query.getResultList();
System.out.println(PracownikWDepartamencie.naglowek());
for (Object row : rows) {
//System.out.println(row);
PracownikWDepartamencie p = (PracownikWDepartamencie)row;
System.out.println(p.dajInfo());
}
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.List;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.Query;
import hr.model.Country;
// Wracając do prostszych rzeczy: Wynik native query można bez problemu odczytać jako normalną encję.
public class Odczyt16_Native_Entity {
public static void main(String[] args) {
final String sql = "SELECT * FROM countries";
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
Query query = em.createNativeQuery(sql, Country.class);
List<Country> rows = (List<Country>)query.getResultList();
for (Country country : rows) {
System.out.println(country.getCountryId() + " " + country.getCountryName());
}
} finally {
if(em != null) em.close();
if(emf != null) emf.close();
}
}
}
package hr.programy;
import java.util.Scanner;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import hr.model.Employee;
public class OdczytajManagerow {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
while(true) {
System.out.print("\nPodaj id pracownika: ");
if(!sc.hasNextInt())
break;
int id = sc.nextInt();
Employee emp = em.find(Employee.class, id);
if(emp == null) {
System.out.println("nie znaleziono takiego pracownika");
continue;
}
while(emp != null) {
System.out.println(" " + emp.getEmployeeId() + " " + emp.getFirstName() + " " + emp.getLastName()
+ "(" + emp.getJob().getJobTitle() + ")" + " $" + emp.getSalary());
emp = emp.getManager();
System.out.println("Managerem jest:");
}
}
} finally {
if(em != null)
em.close();
if(emf != null)
emf.close();
}
}
}
package hr.programy;
import java.util.Scanner;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import hr.model.Department;
import hr.model.Employee;
public class P01_OdczytajWgId {
public static void main(String[] args) {
System.out.println("Startujemy...");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hr_postgresql");
EntityManager em = emf.createEntityManager();
System.out.println("Mam EntityManagera: " + em);
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("\nPodaj ID pracownika (0 kończy program): ");
Integer id = sc.nextInt();
if(id == 0) break;
Employee emp = em.find(Employee.class, id);
System.out.println("Odczytany obiekt: " + emp);
if(emp == null) {
System.out.printf("Nie ma pracownika o id %d\n", id);
continue;
}
System.out.printf("%s %s (%s) zarabia %s\n",
emp.getFirstName(), emp.getLastName(), emp.getJob().getJobTitle(), emp.getSalary());
Department dep = emp.getDepartment();
if(dep != null) {
System.out.printf("Departament %s, %s, %s, %s\n",
dep.getDepartmentName(), dep.getLocation().getStreetAddress(),
dep.getLocation().getCity(), dep.getLocation().getCountry().getCountryName());
}
}
sc.close();
em.close();
emf.close();
System.out.println("Koniec");
}
}
package hr.programy;
import java.util.List;
import hr.model.Location;
import jakarta.persistence.*;
import hr.model.*;
public class P02_OdczytajListe_JPQL {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null ;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
// JPQL = Java Persistence Query Language
TypedQuery<Location> query = em.createQuery("SELECT loc FROM Location loc ORDER BY loc.country.countryId, loc.city", Location.class);
List<Location> locations = query.getResultList();
for (Location loc : locations) {
System.out.printf(" - %s, %s %s, %s\n", loc.getStreetAddress(), loc.getPostalCode(), loc.getCity(),
loc.getCountry().getCountryName());
}
} finally {
em.close();
emf.close();
}
}
}
package hr.programy;
import java.util.List;
import hr.model.Location;
import jakarta.persistence.*;
public class P03_OdczytajListe_NamedQuery {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null ;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
TypedQuery<Location> query = em.createNamedQuery("Location.findAll", Location.class);
List<Location> locations = query.getResultList();
for (Location loc : locations) {
System.out.printf(" - %s, %s %s, %s\n", loc.getStreetAddress(), loc.getPostalCode(), loc.getCity(),
loc.getCountry().getCountryName());
}
} finally {
em.close();
emf.close();
}
}
}
package hr.programy;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import hr.model.Location;
public class P04_OdczytajStream {
public static void main(String[] args) {
// Zapis z użyciem strumienia może dać lepszą wydajność. Zwróć uwagę na kolejność wykonywania dodatkowych selectów
try (EntityManagerFactory emf = Persistence.createEntityManagerFactory("hr_postgresql");
EntityManager em = emf.createEntityManager()) {
em.createNamedQuery("Location.findAll", Location.class)
.getResultStream()
.map(loc -> String.format(" - %s, %s %s, %s", loc.getStreetAddress(), loc.getPostalCode(), loc.getCity(),
loc.getCountry().getCountryName()))
.forEach(System.out::println);
}
}
}
package hr.programy;
import java.util.List;
import javax.swing.JOptionPane;
import hr.model.Employee;
import jakarta.persistence.*;
public class P05_Warunek {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null ;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
String szukaneMiasto = JOptionPane.showInputDialog("Podaj miasto", "Seattle");
TypedQuery<Employee> query = em.createQuery(
"SELECT emp FROM Employee emp WHERE emp.department.location.city = :miasto",
Employee.class);
query.setParameter("miasto", szukaneMiasto);
List<Employee> emps = query.getResultList();
System.out.println("Ilość rekordów " + emps.size());
for (Employee emp : emps) {
System.out.println(emp.getFirstName() + " " + emp.getLastName());
}
} finally {
em.close();
emf.close();
}
}
}
package hr.programy;
import java.math.BigDecimal;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import hr.model.Employee;
public class P06_AktualizujRekord1 {
public static void main(String[] args) {
int id = 100;
int zmiana = 200;
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
em.getTransaction().begin();
Employee emp = em.find(Employee.class, id);
if(emp == null) {
System.out.println("nie ma");
return;
}
System.out.println("Pensja przed zmianą: " + emp.getSalary());
emp.setSalary(emp.getSalary().add(BigDecimal.valueOf(zmiana)));
System.out.println("Pensja po zmianie: " + emp.getSalary());
// flush wykonuje operacje po stronie bazy danych, ale ich nie komituje
//em.flush();
// jeśli robimy commit, to nie potrzebujemy flush
em.getTransaction().commit();
System.out.println("Zapisane");
} finally {
if(em != null)
em.close();
if(emf != null)
emf.close();
}
}
}
package hr.programy;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import hr.model.Department;
import hr.model.Employee;
public class P07_AktualizujRekord2 {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
em.getTransaction().begin();
Employee king = em.find(Employee.class, 100);
System.out.println(king.getEmployeeId() + " " + king.getFirstName() + " " + king.getLastName());
Employee kochhar = em.find(Employee.class, 101);
System.out.println(kochhar.getEmployeeId() + " " + kochhar.getFirstName() + " " + kochhar.getLastName());
Department dep = em.find(Department.class, 90);
System.out.println("departament: " + dep.getDepartmentName());
System.out.println(dep == king.getDepartment());
System.out.println(dep == kochhar.getDepartment());
System.out.println();
System.out.println("Departamenty przed zmianą: "
+ dep.getDepartmentName() + " "
+ king.getDepartment().getDepartmentName() + " "
+ kochhar.getDepartment().getDepartmentName());
king.getDepartment().setDepartmentName("Nowa nazwa");
// king.getDepartment().setDepartmentName("Executive");
System.out.println("Departamenty po zmianie: "
+ dep.getDepartmentName() + " "
+ king.getDepartment().getDepartmentName() + " "
+ kochhar.getDepartment().getDepartmentName());
System.out.println(dep == king.getDepartment());
System.out.println(dep == kochhar.getDepartment());
em.getTransaction().commit();
System.out.println("Zapisane");
} finally {
if(em != null)
em.close();
if(emf != null)
emf.close();
}
}
}
package hr.programy;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import hr.model.Country;
import hr.model.Location;
import hr.model.Region;
public class P08_DodajNoweRekordy {
public static void main(String[] args) {
EntityManagerFactory emf = null;
EntityManager em = null;
try {
emf = Persistence.createEntityManagerFactory("hr_postgresql");
em = emf.createEntityManager();
em.getTransaction().begin();
// Utworzyć nowy kraj (my podajemy id) i nową lokalizację (id zostanie wygenerowane).
Region region = em.find(Region.class, 1);
Country polska = new Country();
polska.setCountryId("PL");
polska.setCountryName("Polska");
polska.setRegion(region);
System.out.println("Zaraz wykonam country.persist...");
em.persist(polska);
System.out.println("Wykonane");
// Dla lokalizacji nie podajemy ID - ono zostanie wygenerowane z sekwencji.
Location loc = new Location();
loc.setCountry(polska);
loc.setStreetAddress("Jasna");
loc.setCity("Warszawa");
loc.setPostalCode("00-123");
System.out.println("id przed dodaniem " + loc.getLocationId());
em.persist(loc);
System.out.println("id po dodaniu " + loc.getLocationId());
em.getTransaction().commit();
System.out.println("Zapisano.");
} finally {
if(em != null)
em.close();
if(emf != null)
emf.close();
}
}
}
package sklep.model; package sklep.model;
import java.io.Serializable;
import jakarta.persistence.*; import jakarta.persistence.*;
import java.util.List;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* The persistent class for the customers database table.
*
*/
@Entity @Entity
@Table(name="customers") @Table(name = "customers")
@NamedQuery(name="Customer.findAll", query="SELECT c FROM Customer c") public class Customer {
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id @Id
@Column(name="customer_email", updatable=false) @Column(name = "customer_email", nullable = false, length = 100)
private String customerEmail; private String customerEmail;
private String address; @Column(name = "customer_name", nullable = false, length = 100)
private String city;
@Column(name="customer_name")
private String customerName; private String customerName;
@Column(name="phone_number") @Column(name = "phone_number", length = 20)
private String phoneNumber; private String phoneNumber;
@Column(name="postal_code") @Column(name = "address", length = 250)
private String address;
@Column(name = "postal_code", length = 10)
private String postalCode; private String postalCode;
//bi-directional many-to-one association to Order @Column(name = "city", length = 100)
@OneToMany(mappedBy="customer") private String city;
private List<Order> orders;
public Customer() { @OneToMany(mappedBy = "customer")
} private Set<Order> orders = new LinkedHashSet<>();
public String getCustomerEmail() { public String getCustomerEmail() {
return this.customerEmail; return customerEmail;
} }
public void setCustomerEmail(String customerEmail) { public void setCustomerEmail(String customerEmail) {
this.customerEmail = customerEmail; this.customerEmail = customerEmail;
} }
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getCustomerName() { public String getCustomerName() {
return this.customerName; return customerName;
} }
public void setCustomerName(String customerName) { public void setCustomerName(String customerName) {
...@@ -72,41 +47,43 @@ public class Customer implements Serializable { ...@@ -72,41 +47,43 @@ public class Customer implements Serializable {
} }
public String getPhoneNumber() { public String getPhoneNumber() {
return this.phoneNumber; return phoneNumber;
} }
public void setPhoneNumber(String phoneNumber) { public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber; this.phoneNumber = phoneNumber;
} }
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPostalCode() { public String getPostalCode() {
return this.postalCode; return postalCode;
} }
public void setPostalCode(String postalCode) { public void setPostalCode(String postalCode) {
this.postalCode = postalCode; this.postalCode = postalCode;
} }
public List<Order> getOrders() { public String getCity() {
return this.orders; return city;
} }
public void setOrders(List<Order> orders) { public void setCity(String city) {
this.orders = orders; this.city = city;
} }
public Order addOrder(Order order) { public Set<Order> getOrders() {
getOrders().add(order); return orders;
order.setCustomer(this);
return order;
} }
public Order removeOrder(Order order) { public void setOrders(Set<Order> orders) {
getOrders().remove(order); this.orders = orders;
order.setCustomer(null);
return order;
} }
} }
\ No newline at end of file
package sklep.model; package sklep.model;
import java.io.Serializable;
import jakarta.persistence.*; import jakarta.persistence.*;
import java.util.Date; import org.hibernate.annotations.ColumnDefault;
import java.sql.Timestamp;
import java.util.List;
import java.time.Instant;
import java.time.LocalDate;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* The persistent class for the orders database table.
*
*/
@Entity @Entity
@Table(name="orders") @Table(name = "orders")
@NamedQuery(name="Order.findAll", query="SELECT o FROM Order o") public class Order {
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="order_id", insertable=false, updatable=false) @ColumnDefault("nextval('orders_seq'::regclass)")
private Integer orderId; @Column(name = "order_id", nullable = false)
private Integer id;
@Temporal(TemporalType.DATE)
@Column(name="delivery_date")
private Date deliveryDate;
@Column(name="order_date") @ManyToOne(fetch = FetchType.LAZY, optional = false)
private Timestamp orderDate; @JoinColumn(name = "customer_email", nullable = false)
private Customer customer;
private String status;
//bi-directional many-to-one association to OrderProduct @ColumnDefault("CURRENT_TIMESTAMP")
@OneToMany(mappedBy="order") @Column(name = "order_date", nullable = false)
private List<OrderProduct> orderProducts; private Instant orderDate;
//bi-directional many-to-one association to Customer @Column(name = "delivery_date")
@ManyToOne private LocalDate deliveryDate;
@JoinColumn(name="customer_email")
private Customer customer;
public Order() { @OneToMany(mappedBy = "order")
} private Set<OrderProduct> orderProducts = new LinkedHashSet<>();
public Integer getOrderId() { public Integer getId() {
return this.orderId; return id;
} }
public void setOrderId(Integer orderId) { public void setId(Integer id) {
this.orderId = orderId; this.id = id;
} }
public Date getDeliveryDate() { public Customer getCustomer() {
return this.deliveryDate; return customer;
} }
public void setDeliveryDate(Date deliveryDate) { public void setCustomer(Customer customerEmail) {
this.deliveryDate = deliveryDate; this.customer = customerEmail;
} }
public Timestamp getOrderDate() { public Instant getOrderDate() {
return this.orderDate; return orderDate;
} }
public void setOrderDate(Timestamp orderDate) { public void setOrderDate(Instant orderDate) {
this.orderDate = orderDate; this.orderDate = orderDate;
} }
public String getStatus() { public LocalDate getDeliveryDate() {
return this.status; return deliveryDate;
} }
public void setStatus(String status) { public void setDeliveryDate(LocalDate deliveryDate) {
this.status = status; this.deliveryDate = deliveryDate;
} }
public List<OrderProduct> getOrderProducts() { public Set<OrderProduct> getOrderProducts() {
return this.orderProducts; return orderProducts;
} }
public void setOrderProducts(List<OrderProduct> orderProducts) { public void setOrderProducts(Set<OrderProduct> orderProducts) {
this.orderProducts = orderProducts; this.orderProducts = orderProducts;
} }
public OrderProduct addOrderProduct(OrderProduct orderProduct) { @ColumnDefault("'NEW'::order_status")
getOrderProducts().add(orderProduct); @Column(name = "status", columnDefinition = "order_status not null")
orderProduct.setOrder(this); @Enumerated(EnumType.STRING)
private Status status;
return orderProduct;
}
public OrderProduct removeOrderProduct(OrderProduct orderProduct) {
getOrderProducts().remove(orderProduct);
orderProduct.setOrder(null);
return orderProduct; public Status getStatus() {
return status;
} }
public Customer getCustomer() { public void setStatus(Status status) {
return this.customer; this.status = status;
} }
public void setCustomer(Customer customer) { public enum Status {
this.customer = customer; NEW,
CONFIRMED,
PAID,
SHIPPED,
DELIVERED,
CLOSED,
RETURNED;
} }
} }
\ No newline at end of file
package sklep.model; package sklep.model;
import java.io.Serializable;
import jakarta.persistence.*; import jakarta.persistence.*;
import java.math.BigDecimal; import org.hibernate.annotations.ColumnDefault;
import java.math.BigDecimal;
/**
* The persistent class for the order_products database table.
*
*/
@Entity @Entity
@Table(name="order_products") @Table(name = "order_products")
@NamedQuery(name="OrderProduct.findAll", query="SELECT o FROM OrderProduct o") public class OrderProduct {
public class OrderProduct implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId @EmbeddedId
private OrderProductPK id; private OrderProductPK id;
@Column(name="actual_price") @MapsId("orderId")
private BigDecimal actualPrice; @ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "order_id", nullable = false)
@Column(name="actual_vat")
private BigDecimal actualVat;
private int quantity;
//bi-directional many-to-one association to Order
@ManyToOne
@JoinColumn(name="order_id")
private Order order; private Order order;
//uni-directional many-to-one association to Product @MapsId("productId")
@ManyToOne @ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name="product_id") @JoinColumn(name = "product_id", nullable = false)
private Product product; private Product product;
public OrderProduct() { @ColumnDefault("1")
} @Column(name = "quantity", nullable = false)
private Short quantity;
@Column(name = "actual_price", nullable = false, precision = 10, scale = 2)
private BigDecimal actualPrice;
@Column(name = "actual_vat", precision = 2, scale = 2)
private BigDecimal actualVat;
public OrderProductPK getId() { public OrderProductPK getId() {
return this.id; return id;
} }
public void setId(OrderProductPK id) { public void setId(OrderProductPK id) {
this.id = id; this.id = id;
} }
public BigDecimal getActualPrice() { public Order getOrder() {
return this.actualPrice; return order;
} }
public void setActualPrice(BigDecimal actualPrice) { public void setOrder(Order order) {
this.actualPrice = actualPrice; this.order = order;
} }
public BigDecimal getActualVat() { public Product getProduct() {
return this.actualVat; return product;
} }
public void setActualVat(BigDecimal actualVat) { public void setProduct(Product product) {
this.actualVat = actualVat; this.product = product;
} }
public int getQuantity() { public Short getQuantity() {
return this.quantity; return quantity;
} }
public void setQuantity(int quantity) { public void setQuantity(Short quantity) {
this.quantity = quantity; this.quantity = quantity;
} }
public Order getOrder() { public BigDecimal getActualPrice() {
return this.order; return actualPrice;
} }
public void setOrder(Order order) { public void setActualPrice(BigDecimal actualPrice) {
this.order = order; this.actualPrice = actualPrice;
} }
public Product getProduct() { public BigDecimal getActualVat() {
return this.product; return actualVat;
} }
public void setProduct(Product product) { public void setActualVat(BigDecimal actualVat) {
this.product = product; this.actualVat = actualVat;
} }
} }
\ No newline at end of file
package sklep.model; package sklep.model;
import java.io.Serializable; import jakarta.persistence.Column;
import jakarta.persistence.*; import jakarta.persistence.Embeddable;
import org.hibernate.Hibernate;
/** import java.util.Objects;
* The primary key class for the order_products database table.
*
*/
@Embeddable
public class OrderProductPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
@Column(name="order_id", insertable=false, updatable=false) @Embeddable
public class OrderProductPK implements java.io.Serializable {
private static final long serialVersionUID = -675988817260271390L;
@Column(name = "order_id", nullable = false)
private Integer orderId; private Integer orderId;
@Column(name="product_id", insertable=false, updatable=false) @Column(name = "product_id", nullable = false)
private Integer productId; private Integer productId;
public OrderProductPK() {
}
public Integer getOrderId() { public Integer getOrderId() {
return this.orderId; return orderId;
} }
public void setOrderId(Integer orderId) { public void setOrderId(Integer orderId) {
this.orderId = orderId; this.orderId = orderId;
} }
public Integer getProductId() { public Integer getProductId() {
return this.productId; return productId;
} }
public void setProductId(Integer productId) { public void setProductId(Integer productId) {
this.productId = productId; this.productId = productId;
} }
public boolean equals(Object other) { @Override
if (this == other) { public boolean equals(Object o) {
return true; if (this == o) return true;
} if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
if (!(other instanceof OrderProductPK)) { OrderProductPK entity = (OrderProductPK) o;
return false; return Objects.equals(this.productId, entity.productId) &&
} Objects.equals(this.orderId, entity.orderId);
OrderProductPK castOther = (OrderProductPK)other;
return
this.orderId.equals(castOther.orderId)
&& this.productId.equals(castOther.productId);
} }
@Override
public int hashCode() { public int hashCode() {
final int prime = 31; return Objects.hash(productId, orderId);
int hash = 17;
hash = hash * prime + this.orderId.hashCode();
hash = hash * prime + this.productId.hashCode();
return hash;
} }
} }
\ No newline at end of file
package sklep.model; package sklep.model;
import java.io.Serializable;
import jakarta.persistence.*; import jakarta.persistence.*;
import java.math.BigDecimal; import org.hibernate.annotations.ColumnDefault;
import java.math.BigDecimal;
/**
* The persistent class for the products database table.
*
*/
@Entity @Entity
@Table(name="products") @Table(name = "products")
@NamedQuery(name="Product.findAll", query="SELECT p FROM Product p") @NamedQuery(name="Product.findAll", query="SELECT p FROM Product p ORDER BY p.id")
public class Product implements Serializable { public class Product {
private static final long serialVersionUID = 1L;
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="product_id", insertable=false, updatable=false) @ColumnDefault("nextval('products_seq'::regclass)")
private Integer productId; @Column(name = "product_id", nullable = false)
private Integer id;
private String description; @Column(name = "product_name", nullable = false, length = 100)
private String productName;
@Column(name = "price", nullable = false, precision = 10, scale = 2)
private BigDecimal price; private BigDecimal price;
@Column(name="product_name") @Column(name = "vat", precision = 2, scale = 2)
private String productName;
private BigDecimal vat; private BigDecimal vat;
public Product() { @Column(name = "description", length = Integer.MAX_VALUE)
} private String description;
public Integer getProductId() { public Integer getId() {
return this.productId; return id;
} }
public void setProductId(Integer productId) { public void setId(Integer id) {
this.productId = productId; this.id = id;
} }
public String getDescription() { public String getProductName() {
return this.description; return productName;
} }
public void setDescription(String description) { public void setProductName(String productName) {
this.description = description; this.productName = productName;
} }
public BigDecimal getPrice() { public BigDecimal getPrice() {
return this.price; return price;
} }
public void setPrice(BigDecimal price) { public void setPrice(BigDecimal price) {
this.price = price; this.price = price;
} }
public String getProductName() { public BigDecimal getVat() {
return this.productName; return vat;
} }
public void setProductName(String productName) { public void setVat(BigDecimal vat) {
this.productName = productName; this.vat = vat;
} }
public BigDecimal getVat() { public String getDescription() {
return this.vat; return description;
} }
public void setVat(BigDecimal vat) { public void setDescription(String description) {
this.vat = vat; this.description = description;
} }
} }
\ No newline at end of file
package sklep.przyklady_hibernate;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import sklep.model.Product;
public class OdczytajListe_Stream {
public static void main(String[] args) {
try(EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep");
EntityManager em = emf.createEntityManager()) {
TypedQuery<Product> query = em.createNamedQuery("Product.findAll", Product.class);
query.getResultStream()
.forEachOrdered(product -> System.out.printf("%s za cenę %s\n",
product.getProductName(), product.getPrice()));
}
}
}
package sklep.przyklady; package sklep.programy;
import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence; import jakarta.persistence.Persistence;
import sklep.model.Product; import sklep.model.Product;
public class P1_OdczytajProdukt { import javax.swing.*;
public class P01_JedenProdukt {
public static void main(String[] args) { public static void main(String[] args) {
System.out.println("Początek programu"); System.out.println("Początek programu");
try(EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep_pu"); EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep_pu");
EntityManager em = emf.createEntityManager()) { System.out.println("Mam factory: " + emf);
System.out.println("Mam em:" + em); EntityManager em = emf.createEntityManager();
Integer id = 1; System.out.println("Mam em: " + em);
Integer id = Integer.valueOf(JOptionPane.showInputDialog("Podaj id produktu"));
Product product = em.find(Product.class, id); Product product = em.find(Product.class, id);
// w razie braku takiego rekordu, wynikiem jest null
if(product == null) { if(product == null) {
System.out.println("Brak produktu o id = " + id); System.out.println("Nie ma produktu o numerze " + id);
} else { } else {
System.out.println("Mam produkt " + product); System.out.println("Odczytany produkt: " + product);
System.out.println(product.getProductName() + " za cenę " + product.getPrice()); System.out.println(product.getProductName() + " za cenę " + product.getPrice());
if(product.getDescription() != null) {
System.out.println(product.getDescription());
} }
} }
System.out.println("Początek programu");
em.close();
emf.close();
} }
} }
package sklep.programy;
import java.util.Scanner;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import sklep.model.Product;
public class P02_OdczytWPetli {
public static void main(String[] args) {
try(Scanner scanner = new Scanner(System.in);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep_pu");
EntityManager em = emf.createEntityManager()) {
while(true) {
System.out.print("\nPodaj id produktu (0 kończy program): ");
int productId = scanner.nextInt();
if (productId == 0) break;
Product product = em.find(Product.class, productId);
if (product == null) {
System.out.println("Nie ma takiego produktu");
continue;
}
System.out.println("Odczytany produkt: " + product);
System.out.println(product.getProductName() + " za cenę " + product.getPrice());
if (product.getDescription() != null) {
System.out.println(product.getDescription());
}
}
}
}
}
package sklep.programy;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import sklep.model.Customer;
import sklep.model.Order;
import sklep.model.OrderProduct;
import java.util.Scanner;
public class P03_OdczytajZamowienie {
public static void main(String[] args) {
try(Scanner scanner = new Scanner(System.in);
EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep_pu");
EntityManager em = emf.createEntityManager()
) {
while(true) {
System.out.print("Podaj nr zamówienia: ");
int id = scanner.nextInt();
if(id == 0) break;
Order order = em.find(Order.class, id);
if(order == null) {
System.out.println("Nie ma zamówienia o numerze " + id);
continue;
}
System.out.println("Odczytany obiekt: " + order);
System.out.println("Zamówienie z dnia " + order.getOrderDate());
if(order.getDeliveryDate() != null) {
System.out.println("Data dostawy: " + order.getDeliveryDate());
}
// Mając wczytany jeden obiekt, możemy za pomocą gettera odczytać obiekt z innej tabeli, który jest powiązany z bieżącym
Customer customer = order.getCustomer();
System.out.println("Odczytany obiekt klienta: " + customer);
System.out.println(customer.getCustomerEmail() + " " + customer.getCustomerName());
System.out.println("Produkty:");
for (OrderProduct op : order.getOrderProducts()) {
System.out.println(" * " + op.getProduct().getProductName() + " za cenę " + op.getActualPrice());
}
System.out.println();
}
}
}
}
package sklep.programy;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import sklep.model.Product;
import java.util.List;
// JPQL = Java (Jakarta) Persistence Query Language
// Język wzorowany na SQL, ale odnoszący się do klas i obiektów w Javie,
// pozwalający wykonywać dowolne zapytania i polecenia na bazie danych poprzez JPA/Hibernate.
public class P04_WszystkieProdukty_JPQL {
public static void main(String[] args) {
try(EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep_pu");
EntityManager em = emf.createEntityManager()
) {
TypedQuery<Product> query = em.createQuery("SELECT p FROM Product p ORDER BY p.id", Product.class);
List<Product> products = query.getResultList();
System.out.println("Odczytano " + products.size() + " rekordów:");
for (Product product : products) {
System.out.println(product.getProductName() + " za cenę " + product.getPrice());
}
}
}
}
package sklep.programy;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import sklep.model.Product;
import java.util.List;
// Często używane zapytania można zdefiniować za pomocą adnotacji @NamedQuery (lub @NamedQueries) w klasach encji,
// a następnie odnosić się do nich w metodzie createNamedQuery
public class P05_WszystkieProdukty_NamedQuery {
public static void main(String[] args) {
try(EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep_pu");
EntityManager em = emf.createEntityManager()
) {
TypedQuery<Product> query = em.createNamedQuery("Product.findAll", Product.class);
List<Product> products = query.getResultList();
System.out.println("Odczytano " + products.size() + " rekordów:");
for (Product product : products) {
System.out.println(product.getProductName() + " za cenę " + product.getPrice());
}
}
}
}
package sklep.programy;
import java.math.BigDecimal;
import java.util.List;
import java.util.Scanner;
import jakarta.persistence.*;
import sklep.model.Product;
public class P06_Parametry {
public static void main(String[] args) {
try (EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep_pu");
EntityManager em = emf.createEntityManager();
Scanner scanner = new Scanner(System.in)) {
System.out.print("Podaj cenę minimalną: ");
BigDecimal min = scanner.nextBigDecimal();
System.out.print("Podaj cenę maksymalną: ");
BigDecimal max = scanner.nextBigDecimal();
TypedQuery<Product> query = em.createQuery(
"SELECT p FROM Product p WHERE p.price BETWEEN :minimum AND :maximum ORDER BY p.price DESC", Product.class);
query.setParameter("minimum", min);
query.setParameter("maximum", max);
List<Product> products = query.getResultList();
for (Product product : products) {
// System.out.println(product);
System.out.println(product.getProductName() + " za cenę " + product.getPrice());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package sklep.programy;
import java.math.BigDecimal;
import java.util.Scanner;
import jakarta.persistence.*;
import sklep.model.Product;
public class P07_Zapis_Update {
public static void main(String[] args) {
try(EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep_pu");
EntityManager em = emf.createEntityManager();
Scanner sc = new Scanner(System.in)) {
System.out.println("Rozpoczynam transakcję");
EntityTransaction transakcja = em.getTransaction();
transakcja.begin();
System.out.println("Aby zakończyć, podaj liczbę 0");
while (true) {
System.out.print("\nPodaj id produktu: ");
int id = sc.nextInt();
sc.nextLine();
if (id == 0) break;
Product product = em.find(Product.class, id);
if (product == null) {
System.out.println("Nie ma produktu o id " + id);
continue;
}
System.out.println("Odczytany produkt: " + product);
System.out.println(product.getProductName() + " za cenę " + product.getPrice() + ", opis: " + product.getDescription());
// Umożliwiamy wprowadzenie zmian i te zmiany są nakładane za pomocą setterów bezpośrednio na obiekcie encji.
System.out.println("Podaj zmianę ceny: ");
BigDecimal zmiana = sc.nextBigDecimal();
sc.nextLine();
if (zmiana.compareTo(BigDecimal.ZERO) != 0) {
product.setPrice(product.getPrice().add(zmiana));
}
System.out.println("Podaj nową nazwę (enter, aby nie zmieniać): ");
String nazwa = sc.nextLine();
if (!nazwa.isEmpty()) {
product.setProductName(nazwa);
}
System.out.println("Podaj nowy opis (enter, aby nie zmieniać): ");
String opis = sc.nextLine();
if (!opis.isEmpty()) {
product.setDescription(opis);
}
}
// Do tej pory zmiany zostały dokonane w obiektach znajdujących się w pamięci.
// Aby zapisać zmiany w bazie danych, należy zatwierdzić transakcję (i tylko tyle).
// To zapisze wszystkie "obiekty zarządzane" przez EntityManagera.
System.out.println("Czy zapisać zmiany? [T/N] ");
String taknie = sc.nextLine().trim().toUpperCase();
switch (taknie) {
case "T", "Y" -> {
transakcja.commit();
System.out.println("Zmiany zatwierdzone");
}
case "N" -> {
transakcja.rollback();
System.out.println("Zmiany wycofane");
}
// w pozostałych przypadkach nie ma ani commit, ani rollback → zmiany nie zostaną zapisane
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package sklep.programy;
import java.math.BigDecimal;
import java.util.Locale;
import java.util.Scanner;
import jakarta.persistence.*;
import sklep.model.Product;
public class P08_Zapis_Insert {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useLocale(Locale.US);
try(EntityManagerFactory emf = Persistence.createEntityManagerFactory("sklep_pu");
EntityManager em = emf.createEntityManager()) {
System.out.println("Początek transakcji");
em.getTransaction().begin();
while (true) {
System.out.print("Podaj nazwę nowego produktu (pusty napis, aby zakończyć): ");
String name = scanner.nextLine();
if (name.isEmpty())
break;
System.out.print("Podaj cenę: ");
BigDecimal price = scanner.nextBigDecimal();
scanner.nextLine();
System.out.print("Podaj stawkę VAT, np 23 : ");
int vat = scanner.nextInt();
scanner.nextLine();
System.out.print("Podaj opis: ");
String description = scanner.nextLine();
if (description.isEmpty()) {
description = null;
}
// aby wpisać rekord do bazy, tworzymy obiekt bez określonego ID
Product product = new Product();
product.setProductName(name);
product.setPrice(price);
product.setVat(BigDecimal.valueOf(vat).movePointLeft(2));
product.setDescription(description);
System.out.printf("Produkt przed persist: id: %s, name: %s, price: %s, vat: %s, desc: %s\n",
product.getId(), product.getProductName(), product.getPrice(), product.getVat(), product.getDescription());
// Dodanie obiektu do puli obiektów zarządzanych i wykonanie INSERT, ale jeszcze bez COMMIT
em.persist(product);
System.out.printf("Produkt po persist: id: %s, name: %s, price: %s, vat: %s, desc: %s\n",
product.getId(), product.getProductName(), product.getPrice(), product.getVat(), product.getDescription());
System.out.println();
}
System.out.println("Czy zapisać zmiany? [T/N]");
String wybor = scanner.next().toUpperCase();
switch (wybor) {
case "T":
System.out.println("Zatwierdzam transakcję");
em.getTransaction().commit();
break;
case "N":
System.out.println("Cofam transakcję");
em.getTransaction().rollback();
break;
default:
System.out.println("Rozłączam się bez zatwierdzenia transakcji");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
...@@ -16,5 +16,19 @@ ...@@ -16,5 +16,19 @@
<property name="hibernate.show_sql" value="true"/> <property name="hibernate.show_sql" value="true"/>
</properties> </properties>
</persistence-unit> </persistence-unit>
<persistence-unit name="hr_postgresql" transaction-type="RESOURCE_LOCAL">
<class>hr.model.Country</class>
<class>hr.model.Department</class>
<class>hr.model.Employee</class>
<class>hr.model.Job</class>
<class>hr.model.Location</class>
<class>hr.model.Region</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/hr"/>
<property name="javax.persistence.jdbc.user" value="alx"/>
<property name="javax.persistence.jdbc.password" value="abc123"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence> </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