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

Hibernate HW #1

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
4 changes: 3 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,9 @@ public EmployerDao(SessionFactory sessionFactory) {
*/
public Employer getEager(int employerId) {
return getSession()
.createQuery("from Employer employer", Employer.class)
.createQuery("from Employer employer join fetch employer.vacancies " +
"where employer.id = :employerId", Employer.class)
.setParameter("employerId", employerId)
.getSingleResult();
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/ru/hh/school/dao/GenericDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void save(Object object) {
if (object == null) {
return;
}
getSession().save(object);
getSession().saveOrUpdate(object);
}

protected Session getSession() {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/ru/hh/school/dao/VacancyDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ 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) " +
"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
8 changes: 8 additions & 0 deletions src/main/java/ru/hh/school/entity/Area.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
package ru.hh.school.entity;

import javax.persistence.*;

//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 String getName() {
Expand Down
11 changes: 10 additions & 1 deletion src/main/java/ru/hh/school/entity/Employer.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,32 @@
package ru.hh.school.entity;

import javax.persistence.*;
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")
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(mappedBy = "employer", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Vacancy> vacancies = new ArrayList<>();

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

public List<Vacancy> getVacancies() {
Expand Down
10 changes: 7 additions & 3 deletions src/main/java/ru/hh/school/entity/Resume.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package ru.hh.school.entity;

import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.*;

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

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

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

Resume() {}
Expand Down
17 changes: 16 additions & 1 deletion src/main/java/ru/hh/school/entity/Vacancy.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,41 @@
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;

@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
2 changes: 2 additions & 0 deletions src/main/java/ru/hh/school/service/EmployerService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package ru.hh.school.service;

import org.hibernate.SessionFactory;
import ru.hh.school.util.TransactionHelper;
import ru.hh.school.dao.EmployerDao;
import ru.hh.school.dao.GenericDao;
Expand Down Expand Up @@ -69,6 +70,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
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static void setupService() {
new EmployerDao(sessionFactory),
new TransactionHelper(sessionFactory)
);
TestHelper.executeScript(pg.getPostgresDatabase(), "create_employers.sql");
TestHelper.executeScript(dataSource, "create_employers.sql");
}

@Test
Expand Down
4 changes: 2 additions & 2 deletions src/test/java/ru/hh/school/service/VacancyServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ public static void setupService() {
new VacancyDao(sessionFactory),
new TransactionHelper(sessionFactory)
);
TestHelper.executeScript(pg.getPostgresDatabase(), "create_employers.sql");
TestHelper.executeScript(dataSource, "create_employers.sql");
}

@Test
public void getSalaryStatistics() {
TestHelper.executeScript(pg.getPostgresDatabase(), "clear_data.sql");
TestHelper.executeScript(dataSource, "clear_data.sql");

Employer employer = new Employer();
employer.setCompanyName("HH");
Expand Down