Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

оформлены сущности, поправлены методы и генерация сиквенса #4

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions src/main/java/ru/hh/school/dao/EmployerDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ public EmployerDao(SessionFactory sessionFactory) {
}

/**
* TODO: здесь нужен метод, позволяющий сразу загрузить вакасии, связанные с работодателем и в некоторых случаях
* TODO: здесь нужен метод, позволяющий сразу загрузить вакансии, связанные с работодателем и в некоторых случаях
* избежать org.hibernate.LazyInitializationException
* Также в запрос должен передаваться параметр employerId
* <p>
* https://vladmihalcea.com/the-best-way-to-handle-the-lazyinitializationexception/
*/
public Employer getEager(int employerId) {
return getSession()
.createQuery("from Employer employer", Employer.class)
.createQuery("SELECT employer FROM Employer AS employer " +
"JOIN FETCH employer.vacancies " +
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше LEFT join fetch, иначе не будут выбираться работодатели без вакансий

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

осознал, исправил

"WHERE employer.id = :employerId ", Employer.class)
.setParameter("employerId", employerId)
.getSingleResult();
}

Expand Down
9 changes: 7 additions & 2 deletions src/main/java/ru/hh/school/dao/GenericDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
import org.hibernate.SessionFactory;

import java.io.Serializable;
import java.util.Collection;
import java.util.Objects;

public class GenericDao {
private final SessionFactory sessionFactory;
Expand All @@ -28,6 +26,13 @@ public void save(Object object) {
getSession().save(object);
}

public void update(Object object) {
if (object == null) {
return;
}
getSession().update(object);
}

protected Session getSession() {
return sessionFactory.getCurrentSession();
}
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/ru/hh/school/dao/VacancyDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@
import ru.hh.school.employers.StatisticsDto;
import ru.hh.school.entity.Area;

public class VacancyDao extends GenericDao{
public class VacancyDao extends GenericDao {
public VacancyDao(SessionFactory sessionFactory) {
super(sessionFactory);
}

public StatisticsDto getSalaryStatistics(Area area){
public StatisticsDto getSalaryStatistics(Area area) {
// ToDo дополните запрос, чтобы возвращался ru.hh.school.employers.StatisticsDto
// https://vladmihalcea.com/the-best-way-to-map-a-projection-query-to-a-dto-with-jpa-and-hibernate/
return getSession().createQuery(
"SELECT count(v.id), min(v.compensationFrom), max(v.compensationTo) " +
"FROM Vacancy v WHERE v.area = :area", StatisticsDto.class)
"SELECT new ru.hh.school.employers.StatisticsDto(count(v.id), min(v.compensationFrom), max(v.compensationTo)) " +
"FROM Vacancy v WHERE v.area = :area", StatisticsDto.class)
.setParameter("area", area)
.getSingleResult();
}
Expand Down
40 changes: 40 additions & 0 deletions src/main/java/ru/hh/school/entity/Area.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,56 @@
package ru.hh.school.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Objects;

//TODO: оформите entity
@Entity
@Table(name = "area")
public class Area {

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

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

public Area() {
}

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

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

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Area area = (Area) o;
return Objects.equals(id, area.id) && Objects.equals(name, area.name);
}

@Override
public int hashCode() {
return Objects.hash(id, name);
}

}
46 changes: 41 additions & 5 deletions src/main/java/ru/hh/school/entity/Employer.java
Original file line number Diff line number Diff line change
@@ -1,33 +1,53 @@
package ru.hh.school.entity;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

//TODO: оформите entity
@Entity
@Table(name = "employer")
public class Employer {

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

@Column(name = "company_name", nullable = false, length = 100)
private String companyName;

// не используйте java.util.Date
// https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#basic-datetime-java8
@Column(name = "creation_time")
private LocalDateTime creationTime;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "employer")
private List<Vacancy> vacancies = new ArrayList<>();

@Column(name = "block_time")
private LocalDateTime blockTime;

public List<Vacancy> getVacancies() {
return vacancies;
public Employer() {
}

public Integer getId() {
return id;
}

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

public String getCompanyName() {
return companyName;
}
Expand All @@ -36,6 +56,22 @@ public void setCompanyName(String companyName) {
this.companyName = companyName;
}

public LocalDateTime getCreationTime() {
return creationTime;
}

public void setCreationTime(LocalDateTime creationTime) {
this.creationTime = creationTime;
}

public List<Vacancy> getVacancies() {
return vacancies;
}

public void setVacancies(List<Vacancy> vacancies) {
this.vacancies = vacancies;
}

public LocalDateTime getBlockTime() {
return blockTime;
}
Expand All @@ -48,17 +84,17 @@ public void setBlockTime(LocalDateTime blockTime) {
//
// https://vladmihalcea.com/hibernate-facts-equals-and-hashcode/
// https://docs.jboss.org/hibernate/orm/5.3/userguide/html_single/Hibernate_User_Guide.html#mapping-model-pojo-equalshashcode

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employer employer = (Employer) o;
return Objects.equals(companyName, employer.companyName);
return Objects.equals(id, employer.id) && Objects.equals(companyName, employer.companyName) && Objects.equals(creationTime, employer.creationTime) && Objects.equals(vacancies, employer.vacancies) && Objects.equals(blockTime, employer.blockTime);
}

@Override
public int hashCode() {
return Objects.hash(companyName);
return Objects.hash(id, companyName, creationTime, vacancies, blockTime);
}

}
44 changes: 42 additions & 2 deletions src/main/java/ru/hh/school/entity/Resume.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
package ru.hh.school.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import java.util.Objects;

//TODO: оформите entity
@Entity
@Table(name = "resume")
public class Resume {
// TODO: сделать так, чтобы id брался из sequence-а
// таким образом, мы сможем отправлять в бд запросы батчами.
Expand All @@ -15,15 +23,47 @@ public class Resume {
// https://vladmihalcea.com/from-jpa-to-hibernates-legacy-and-enhanced-identifier-generators/

@Id
@GeneratedValue(/* здесь место для вашего кода */)
@GeneratedValue(generator = "sequence", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "sequence", sequenceName = "resume_id_seq", allocationSize = 10)
@Column(name = "resume_id")
private Integer id;

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

Resume() {}
public Resume() {
}

public Resume(String description) {
this.description = description;
}

public Integer getId() {
return id;
}

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

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Resume resume = (Resume) o;
return Objects.equals(id, resume.id) && Objects.equals(description, resume.description);
}

@Override
public int hashCode() {
return Objects.hash(id, description);
}
}
21 changes: 18 additions & 3 deletions src/main/java/ru/hh/school/entity/Vacancy.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,42 @@
import java.util.Objects;

//TODO: оформите entity
@Entity
@Table(name = "vacancy")
public class Vacancy {

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

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "employer_id", nullable = false)
private Employer employer;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "area_id")
private Area area;

@Column(name = "title", nullable = false, length = 100)
private String title;

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

@Column(name = "compensation_from")
private Integer compensationFrom;

@Column(name = "compensation_to")
private Integer compensationTo;

@Column(name = "compensation_gross")
private Boolean compensationGross;

@Column(name = "creation_time")
private LocalDateTime creationTime;

@Column(name = "archiving_time")
private LocalDateTime archivingTime;

public Vacancy() {
Expand Down Expand Up @@ -95,12 +111,11 @@ public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vacancy vacancy = (Vacancy) o;
return Objects.equals(id, vacancy.id);
return Objects.equals(id, vacancy.id) && Objects.equals(employer, vacancy.employer) && Objects.equals(area, vacancy.area) && Objects.equals(title, vacancy.title) && Objects.equals(description, vacancy.description) && Objects.equals(compensationFrom, vacancy.compensationFrom) && Objects.equals(compensationTo, vacancy.compensationTo) && Objects.equals(compensationGross, vacancy.compensationGross) && Objects.equals(creationTime, vacancy.creationTime) && Objects.equals(archivingTime, vacancy.archivingTime);
}

@Override
public int hashCode() {
return 17;
return Objects.hash(id, employer, area, title, description, compensationFrom, compensationTo, compensationGross, creationTime, archivingTime);
}

}
1 change: 1 addition & 0 deletions src/main/java/ru/hh/school/service/EmployerService.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ public void blockIfEmployerUseBadWords(int employerId) {
transactionHelper.inTransaction(() -> {
employer.setBlockTime(LocalDateTime.now());
employer.getVacancies().forEach(v -> v.setArchivingTime(LocalDateTime.now()));
genericDao.update(employer);
});
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/scripts/create_resume.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ create sequence resume_id_seq
increment by 10;

create table resume (
id int not null default nextval('resume_id_seq') primary key,
resume_id int not null default nextval('resume_id_seq') primary key,
description text
);