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

HeadHunterSchool13_HomeWork03_Hibernate #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# Project exclude paths
/target/
/target/
.idea
6 changes: 3 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.opentable.components</groupId>
<artifactId>otj-pg-embedded</artifactId>
<version>0.13.0</version>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.17.6</version>
<scope>test</scope>
</dependency>

Expand Down
5 changes: 4 additions & 1 deletion src/main/java/ru/hh/school/DbFactory.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package ru.hh.school;

import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import ru.hh.school.entity.Resume;
import ru.hh.school.entity.Area;
import ru.hh.school.entity.Employer;
Expand All @@ -19,9 +21,10 @@ public class DbFactory {
Area.class
);

public static SessionFactory createSessionFactory() {
public static SessionFactory createSessionFactory(DataSource dataSource) {
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.loadProperties("hibernate.properties")
.applySetting(Environment.DATASOURCE, dataSource)
.build();

MetadataSources metadataSources = new MetadataSources(serviceRegistry);
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/ru/hh/school/dao/EmployerDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ public EmployerDao(SessionFactory sessionFactory) {
*/
public Employer getEager(int employerId) {
return getSession()
.createQuery("from Employer employer", Employer.class)
.createQuery(
"SELECT e FROM Employer AS e " +
" LEFT JOIN FETCH e.vacancies" +
" WHERE e.id = :eid", Employer.class)
.setParameter("eid", employerId)
.getSingleResult();
}

Expand Down
5 changes: 1 addition & 4 deletions src/main/java/ru/hh/school/dao/GenericDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@

import org.hibernate.Session;
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 @@ -25,7 +22,7 @@ public void save(Object object) {
if (object == null) {
return;
}
getSession().save(object);
getSession().saveOrUpdate(object);
}

protected Session getSession() {
Expand Down
9 changes: 5 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,18 @@
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 AS v " +
"WHERE v.area = :area", StatisticsDto.class)
.setParameter("area", area)
.getSingleResult();
}
Expand Down
34 changes: 33 additions & 1 deletion src/main/java/ru/hh/school/entity/Area.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,48 @@
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;

//TODO: оформите entity
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "area_id")
private Integer id;

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

public Area() {
}

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 name.equals(area.getName());
}

@Override
public int hashCode() {
int hash = id * id;
hash = 31 * hash + (name == null ? 0 : name.hashCode());
return 31 * hash;
}
}
36 changes: 31 additions & 5 deletions src/main/java/ru/hh/school/entity/Employer.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,45 @@
package ru.hh.school.entity;

import com.sun.istack.NotNull;
import org.hibernate.annotations.CreationTimestamp;

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")
@NotNull
private String companyName;

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

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

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

public List<Vacancy> getVacancies() {
Expand Down Expand Up @@ -48,17 +70,21 @@ 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 id.equals(employer.getId()) && companyName.equals(employer.getCompanyName());
}

@Override
public int hashCode() {
return Objects.hash(companyName);
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (companyName != null ? companyName.hashCode() : 0);
return result;
}

}
13 changes: 11 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,16 @@
package ru.hh.school.entity;

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

//TODO: оформите entity
@Entity
@Table(name = "resume")
public class Resume {
// TODO: сделать так, чтобы id брался из sequence-а
// таким образом, мы сможем отправлять в бд запросы батчами.
Expand All @@ -15,12 +22,14 @@ 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)
private Integer id;

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

Resume() {}
public Resume() {}

public Resume(String description) {
this.description = description;
Expand Down
30 changes: 24 additions & 6 deletions src/main/java/ru/hh/school/entity/Vacancy.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,43 @@
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.time.LocalDateTime;
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")
private Employer employer;

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

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

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

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

private Integer compensationTo;
@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 @@ -94,13 +108,17 @@ public void setArchivingTime(LocalDateTime archivingTime) {
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 id.equals(vacancy.getId()) && title.equals(vacancy.getTitle());
}

@Override
public int hashCode() {
return 17;
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (title != null ? title.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
return result;
}

}
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.save(employer);
});
}

Expand Down
1 change: 0 additions & 1 deletion src/main/resources/hibernate.properties
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# datasource
hibernate.connection.driver_class = org.postgresql.Driver
hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
hibernate.connection.url = jdbc:postgresql://localhost:5433/postgres
hibernate.connection.username = postgres
hibernate.connection.password = postgres
hibernate.current_session_context_class=thread
Expand Down
22 changes: 18 additions & 4 deletions src/test/java/ru/hh/school/BaseTest.java
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
package ru.hh.school;

import com.opentable.db.postgres.embedded.EmbeddedPostgres;
import javax.sql.DataSource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Before;
import org.junit.BeforeClass;
import org.postgresql.ds.PGSimpleDataSource;
import org.testcontainers.containers.PostgreSQLContainer;
import ru.hh.school.util.QueryInfoHolder;
import java.io.IOException;
import java.util.Optional;
import java.util.function.Supplier;

public abstract class BaseTest {

protected static EmbeddedPostgres pg;
protected static PostgreSQLContainer pgContainer;
protected static DataSource dataSource;
protected static SessionFactory sessionFactory;

@BeforeClass
public static void setupSessionFactory() throws IOException {
pg = EmbeddedPostgres.builder().setPort(5433).start();
sessionFactory = DbFactory.createSessionFactory();
pgContainer = new PostgreSQLContainer<>("postgres")
.withUsername("postgres")
.withPassword("postgres");
pgContainer.start();

PGSimpleDataSource pgDataSource = new PGSimpleDataSource();
String jdbcUrl = pgContainer.getJdbcUrl();
pgDataSource.setUrl(jdbcUrl);
pgDataSource.setUser(pgContainer.getUsername());
pgDataSource.setPassword(pgContainer.getPassword());
dataSource = pgDataSource;

sessionFactory = DbFactory.createSessionFactory(dataSource);
}

@Before
Expand Down
4 changes: 2 additions & 2 deletions src/test/java/ru/hh/school/batching/BatchingTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ public class BatchingTest extends BaseTest {

@BeforeClass
public static void createTable() {
TestHelper.executeScript(pg.getPostgresDatabase(), "create_resume.sql");
TestHelper.executeScript(dataSource, "create_resume.sql");
}

@Before
public void clearTable() {
TestHelper.execute(pg.getPostgresDatabase(), "delete from resume");
TestHelper.execute(dataSource, "delete from resume");
}

/**
Expand Down
Loading