Проблемы с репозиториями застройщика, валидации и JPA в приложении Java Spring Boot ApplicationJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Проблемы с репозиториями застройщика, валидации и JPA в приложении Java Spring Boot Application

Сообщение Anonymous »

Я работаю над приложением Java Spring Boot для системы аренды недвижимости. Проект использует JPA, MySQL, разработку тестирования (TDD) и шаблон застройщика. Если проверка не удается, я должен вернуть NULL вместо того, чтобы бросить исключение. /> Проблемы и вопросы:
Обработка проверки:
возвращает NULL из метода завода. Лучший способ справиться с неудачной проверкой? Может ли это создать скрытые ошибки позже? Есть ли лучшие способы создания подклассов (например, дома и квартиры) с общими атрибутами родительского класса? Должен ли я создать более общие интерфейсы обслуживания или специфичные для домена? Слои?package za.co.property365.domain;

import jakarta.persistence.Entity;

@Entity
public class Apartment extends Property {

private String apartmentName;
private String apartmentNumber;
private int floorNumber;

protected Apartment(Builder builder) {
this.propertyId = builder.propertyId;
this.streetNumber = builder.streetNumber;
this.streetName = builder.streetName;
this.suburb = builder.suburb;
this.city = builder.city;
this.postalCode = builder.postalCode;
this.rentalCost = builder.rentalCost;
this.apartmentName = builder.apartmentName;
this.apartmentNumber = builder.apartmentNumber;
this.floorNumber = builder.floorNumber;
}

public Apartment() {

}

public Long getPropertyId() {
return propertyId;
}
public String getStreetNumber() {
return streetNumber;
}
public String getStreetName() {
return streetName;
}
public String getSuburb() {
return suburb;
}
public String getCity() {
return city;
}
public int getPostalCode() {
return postalCode;
}
public double getRentalCost() {
return rentalCost;
}
public String getApartmentName() {
return apartmentName;
}
public String getApartmentNumber() {
return apartmentNumber;
}
public int getFloorNumber() {
return floorNumber;
}
@Override
public String toString() {
return "Apartment{" +
"apartmentName='" + apartmentName + '\'' +
", apartmentNumber='" + apartmentNumber + '\'' +
", floorNumber=" + floorNumber +
", propertyId=" + propertyId +
", streetNumber='" + streetNumber + '\'' +
", streetName='" + streetName + '\'' +
", suburb='" + suburb + '\'' +
", city='" + city + '\'' +
", postalCode=" + postalCode +
", rentalCost=" + rentalCost +
'}';
}

public static class Builder {
private long propertyId;
private String streetNumber;
private String streetName;
private String suburb;
private String city;
private int postalCode;
private double rentalCost;
private String apartmentName;
private String apartmentNumber;
private int floorNumber;

public Builder propertyId(long propertyId) {
this.propertyId = propertyId;
return this;
}

public Builder streetNumber(String streetNumber) {
this.streetNumber = streetNumber;
return this;
}

public Builder streetName(String streetName) {
this.streetName = streetName;
return this;
}

public Builder suburb(String suburb) {
this.suburb = suburb;
return this;
}

public Builder city(String city) {
this.city = city;
return this;
}

public Builder postalCode(int postalCode) {
this.postalCode = postalCode;
return this;
}

public Builder rentalCost(double rentalCost) {
this.rentalCost = rentalCost;
return this;
}

public Builder apartmentName(String apartmentName) {
this.apartmentName = apartmentName;
return this;
}

public Builder apartmentNumber(String apartmentNumber) {
this.apartmentNumber = apartmentNumber;
return this;
}

public Builder floorNumber(int floorNumber) {
this.floorNumber = floorNumber;
return this;
}

public Apartment build() {
return new Apartment(this);
}

public Builder copy(Apartment apartment) {
this.propertyId = apartment.propertyId;
this.streetNumber = apartment.streetNumber;
this.streetName = apartment.streetName;
this.suburb = apartment.suburb;
this.city = apartment.city;
this.postalCode = apartment.postalCode;
this.rentalCost = apartment.rentalCost;
this.apartmentName = apartment.apartmentName;
this.apartmentNumber = apartment.apartmentNumber;
this.floorNumber = apartment.floorNumber;
return this;
}
}
}
< /code>
Квартовая фабрика: < /p>
package za.co.property365.factory;

import za.co.property365.domain.Apartment;
import za.co.property365.util.Helper;

public class ApartmentFactory {

public static Apartment createApartment(String streetNumber, String streetName, String suburb, String city, int postalCode, double rentalCost,
String apartmentName, String apartmentNumber, int floorNumber) {
if (Helper.isNullOrEmpty(streetNumber) || Helper.isNullOrEmpty(streetName) || Helper.isNullOrEmpty(suburb) || Helper.isNullOrEmpty(city)
|| !Helper.isValidPostalCode(postalCode) || !Helper.isValidRentalCost(rentalCost)) {
return null;
}
Apartment apartment = new Apartment.Builder()
.streetNumber(streetNumber)
.streetName(streetName)
.suburb(suburb)
.city(city)
.postalCode(postalCode)
.rentalCost(rentalCost)
.apartmentName(apartmentName)
.apartmentNumber(apartmentNumber)
.floorNumber(floorNumber)
.build();

return apartment;
}
}
< /code>
Репозиторий квартир: < /p>
package za.co.property365.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import za.co.property365.domain.Apartment;

import java.util.List;

@Repository
public interface ApartmentRepository extends JpaRepository {

List findBySuburb(String suburb);

List findByCity(String city);

List findByRentalCostLessThan(double maxRentalCost);

List findByApartmentName(String apartmentName);
}
< /code>
Apartment Service: < /p>
package za.co.property365.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import za.co.property365.domain.Apartment;
import za.co.property365.repository.ApartmentRepository;

import java.util.List;

@Service
public class ApartmentService {
private final ApartmentRepository apartmentRepository;

public ApartmentService(ApartmentRepository apartmentRepository) {
this.apartmentRepository = apartmentRepository;
}

public Apartment save(Apartment apartment) {
return apartmentRepository.save(apartment);
}

public void deleteById(Long id) {
apartmentRepository.deleteById(id);
}

public Apartment findById(Long id) {
return apartmentRepository.findById(id).orElse(null);
}

public List findAll() {
return apartmentRepository.findAll();
}

public List findBySuburb(String suburb) {
return apartmentRepository.findBySuburb(suburb);
}

public List findByCity(String city) {
return apartmentRepository.findByCity(city);
}

public List findByRentalCostLessThan(double maxRentalCost) {
return apartmentRepository.findByRentalCostLessThan(maxRentalCost);
}

public List findByApartmentName(String apartmentName) {
return apartmentRepository.findByApartmentName(apartmentName);
}
}
< /code>
Служба iapartment: < /p>
package za.co.property365.service;

import za.co.property365.domain.Apartment;

import java.util.List;

/**
* IApartmentService.java
* ToDo: Also include method declarations for - findBySuburb, findByRentalCostLessThan
*/

public interface IApartmentService {

Apartment save(Apartment apartment);

void deleteById(Long id);

Apartment findById(Long id);

List findAll();

List findBySuburb(String suburb);

List findByRentalCostLessThan(double maxRentalCost);
}
< /code>
iservice: < /p>
package za.co.property365.service;

import java.util.List;

public interface IService {
T save(T entity);
T findById(ID id);
void deleteById(ID id);
List findAll();
}
< /code>
Дом дома: < /p>
package za.co.property365.domain;

import jakarta.persistence.Entity;

@Entity
public class House extends Property {

private int erfSize;

public House() {
}

protected House(Builder builder) {
this.erfSize = builder.erfSize;
this.propertyId = builder.propertyId;
this.streetNumber = builder.streetNumber;
this.streetName = builder.streetName;
this.suburb = builder.suburb;
this.city = builder.city;
this.postalCode = builder.postalCode;
this.rentalCost = builder.rentalCost;

}

public int getErfSize() {
return erfSize;
}
public Long getPropertyId() {
return propertyId;
}
public String getStreetNumber() {
return streetNumber;
}
public String getStreetName() {
return streetName;
}
public String getSuburb() {
return suburb;
}
public String getCity() {
return city;
}
public int getPostalCode() {
return postalCode;
}
public double getRentalCost() {
return rentalCost;
}
@Override
public String toString() {
return "House{" +
"erfSize=" + erfSize +
", propertyId=" + propertyId +
", streetNumber='" + streetNumber + '\'' +
", streetName='" + streetName + '\'' +
", suburb='" + suburb + '\'' +
", city='" + city + '\'' +
", postalCode=" + postalCode +
", rentalCost=" + rentalCost +
'}';
}

public static class Builder {
private int erfSize;
private long propertyId;
private String streetNumber;
private String streetName;
private String suburb;
private String city;
private int postalCode;
private double rentalCost;

public Builder erfSize(int erfSize) {
this.erfSize = erfSize;
return this;
}

public Builder propertyId(long propertyId) {
this.propertyId = propertyId;
return this;
}

public Builder streetNumber(String streetNumber) {
this.streetNumber = streetNumber;
return this;
}

public Builder streetName(String streetName) {
this.streetName = streetName;
return this;
}

public Builder suburb(String suburb) {
this.suburb = suburb;
return this;
}

public Builder city(String city) {
this.city = city;
return this;
}

public Builder postalCode(int postalCode) {
this.postalCode = postalCode;
return this;
}

public Builder rentalCost(double rentalCost) {
this.rentalCost = rentalCost;
return this;
}

public House build() {
return new House(this);
}
}

public Builder copy() {
return new Builder()
.erfSize(this.erfSize)
.propertyId(this.propertyId)
.streetNumber(this.streetNumber)
.streetName(this.streetName)
.suburb(this.suburb)
.city(this.city)
.postalCode(this.postalCode)
.rentalCost(this.rentalCost);
}

}
< /code>
House Factory: < /p>
package za.co.property365.factory;

import za.co.property365.domain.House;
import za.co.property365.util.Helper;

public class HouseFactory {

public static String createHouse(String streetNumber, String streetName, String suburb, String city, int postalCode, double rentalCost) {
if (Helper.isNullOrEmpty(streetNumber)|| Helper.isNullOrEmpty(streetName) || Helper.isNullOrEmpty(suburb) || Helper.isNullOrEmpty(city) || !Helper.isValidPostalCode(postalCode) || !Helper.isValidRentalCost(rentalCost)) {
return null;
}

return
new House.Builder()
.streetNumber(streetNumber)
.streetName(streetName)
.suburb(suburb)
.city(city)
.postalCode(postalCode)
.rentalCost(rentalCost)
.build()
.toString();
}
}
< /code>
House Repository: < /p>
package za.co.property365.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import za.co.property365.domain.House;

import java.util.List;

@Repository
public interface HouseRepository extends JpaRepository {
List findBySuburb(String suburb);
List findByCity(String city);
List findByRentalCostLessThan(double maxRentalCost);
List findByStreetName(String streetName);
}
< /code>
House Service: < /p>
package za.co.property365.service;

import org.springframework.stereotype.Service;
import za.co.property365.domain.House;
import za.co.property365.repository.HouseRepository;

import java.util.List;

@Service
public class HouseService {
private final HouseRepository houseRepository;

public HouseService(HouseRepository houseRepository) {
this.houseRepository = houseRepository;
}

public House save(House house) {
return houseRepository.save(house);
}

public void deleteById(Long id) {
houseRepository.deleteById(id);
}

public House findById(Long id) {
return houseRepository.findById(id).orElse(null);
}

public List findAll() {
return houseRepository.findAll();
}

public List findBySuburb(String suburb) {
return houseRepository.findBySuburb(suburb);
}

public List findByCity(String city) {
return houseRepository.findByCity(city);
}

public List findByRentalCostLessThan(double maxRentalCost) {
return houseRepository.findByRentalCostLessThan(maxRentalCost);
}

public List findByStreetName(String streetName) {
return houseRepository.findByStreetName(streetName);
}
}
< /code>
ihouse service: < /p>
package za.co.property365.service;

import za.co.property365.domain.House;

import java.util.List;

/**
* IHouseService.java
* ToDo: Also include method declarations for - findBySuburb, findByRentalCostLessThan
*/
public interface IHouseService {
House save(House house);
void deleteById(Long id);
House findById(Long id);
List findAll();
List findBySuburb(String suburb);
List findByRentalCostLessThan(double maxRentalCost);
List findByCity(String city);
List findByStreetName(String streetName);
}
< /code>
контроллер дома: < /p>
package za.co.property365.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import za.co.property365.domain.House;
import za.co.property365.repository.HouseRepository;

import java.util.List;

@RestController
@RequestMapping("/houses")
public class HouseController {
private final HouseRepository houseRepository;

@Autowired
public HouseController(HouseRepository houseRepository) {
this.houseRepository = houseRepository;
}

@GetMapping
public List getAllHouses() {
return houseRepository.findAll();
}

@GetMapping("/{id}")
public House getHouseById(@PathVariable Long id) {
return houseRepository.findById(id).orElse(null);
}

@PostMapping
public House createHouse(@RequestBody House house) {
return houseRepository.save(house);
}

@PutMapping("/{id}")
public House updateHouse(@PathVariable Long id, @RequestBody House house) {
house.setPropertyId(id);
return houseRepository.save(house);
}

@DeleteMapping("/{id}")
public void deleteHouse(@PathVariable Long id) {
houseRepository.deleteById(id);
}

@GetMapping("/suburb/{suburb}")
public List getHousesBySuburb(@PathVariable String suburb) {
return houseRepository.findBySuburb(suburb);
}

@GetMapping("/city/{city}")
public List getHousesByCity(@PathVariable String city) {
return houseRepository.findByCity(city);
}

@GetMapping("/rental/less-than/{cost}")
public List getHousesByRentalCostLessThan(@PathVariable double cost) {
return houseRepository.findByRentalCostLessThan(cost);
}

@GetMapping("/street/{streetName}")
public List getHousesByStreetName(@PathVariable String streetName) {
return houseRepository.findByStreetName(streetName);
}
}
< /code>
Имя домен: < /p>
package za.co.property365.domain;

public class Name implements ValueObject{

private String firstName;
private String middleName;
private String lastName;

private Name() {
}

protected Name(Builder builder) {
this.firstName = builder.firstName;
this.middleName = builder.middleName;
this.lastName = builder.lastName;
}

public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}

@Override
public String toString() {
return "Name{" +
"firstName='" + firstName + '\'' +
", middleName='" + middleName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}

public static class Builder {
private String firstName;
private String middleName;
private String lastName;

public Builder firstName(String firstName) {
this.firstName = firstName;
return this;
}

public Builder middleName(String middleName) {
this.middleName = middleName;
return this;
}

public Builder lastName(String lastName) {
this.lastName = lastName;
return this;
}

public Name build() {
return new Name(this);
}

public Builder copy(Name name) {
this.firstName = name.firstName;
this.middleName = name.middleName;
this.lastName = name.lastName;
return this;
}
}
}
< /code>
Домен свойства: < /p>
package za.co.property365.domain;

import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;

@MappedSuperclass
public abstract class Property {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected long propertyId;
protected String streetNumber;
protected String streetName;
protected String suburb;
protected String city;
protected int postalCode;
protected double rentalCost;

public void setPropertyId(Long propertyId) {
this.propertyId = propertyId;
}

@Override
public String toString() {
return "Property{" +
"propertyId=" + propertyId +
", streetNumber='" + streetNumber + '\'' +
", streetName='" + streetName + '\'' +
", suburb='" + suburb + '\'' +
", city='" + city + '\'' +
", postalCode=" + postalCode +
", rentalCost=" + rentalCost +
'}';
}
}
< /code>
Домен агента аренды: < /p>
package za.co.property365.domain;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;

@Entity
public class RentalAgent {

@Id
private String name;
private String email;
private String mobile;

public RentalAgent() {
}

protected RentalAgent(Builder builder) {
this.name = builder.name;
this.email = builder.email;
this.mobile = builder.mobile;

}

public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getMobile() {
return mobile;
}
@Override
public String toString() {
return "RentalAgent{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", mobile='" + mobile + '\'' +
'}';
}

public static class Builder {
private String name;
private String email;
private String mobile;

public Builder name(String name) {
this.name = name;
return this;
}

public Builder email(String email) {
this.email = email;
return this;
}

public Builder mobile(String mobile) {
this.mobile = mobile;
return this;
}

public RentalAgent build() {
return new RentalAgent(this);
}

public Builder copy(RentalAgent rentalAgent) {
this.name = rentalAgent.name;
this.email = rentalAgent.email;
this.mobile = rentalAgent.mobile;
return this;
}
}
}
< /code>
Агентство арендованного агентства: < /pbr /> package za.co.property365.factory;

import za.co.property365.domain.RentalAgent;
import za.co.property365.util.Helper;

public class RentalAgentFactory {

public static RentalAgent createRentalAgent(String name, String email, String mobile) {

if (Helper.isNullOrEmpty(name) || Helper.isNullOrEmpty(email) || Helper.isNullOrEmpty(mobile)){

return null;
}

if (!Helper.isValidEmail(email)) {
return null;
}

if (!Helper.isValidMobile(mobile)) {
return null;
}
return new RentalAgent.Builder()
.name(name)
.email(email)
.mobile(mobile)
.build();
}
}
< /code>
Репозиторий агентства аренды: < /pbr /> package za.co.property365.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import za.co.property365.domain.RentalAgent;

import java.util.List;

@Repository
public interface RentalAgentRepository extends JpaRepository {
List findByName(String name);
List findByEmail(String email);
List findByMobile(String mobile);
}
< /code>
Служба аренды агентства: < /pbr /> package za.co.property365.service;

import org.springframework.stereotype.Service;
import za.co.property365.domain.RentalAgent;
import za.co.property365.repository.RentalAgentRepository;

import java.util.List;

@Service
public class RentalAgentService {
private final RentalAgentRepository rentalAgentRepository;

public RentalAgentService(RentalAgentRepository rentalAgentRepository) {
this.rentalAgentRepository = rentalAgentRepository;
}

public RentalAgent save(RentalAgent agent) {
return rentalAgentRepository.save(agent);
}

public void deleteById(String id) {
rentalAgentRepository.deleteById(id);
}

public RentalAgent findById(String id) {
return rentalAgentRepository.findById(id).orElse(null);
}

public List findAll() {
return rentalAgentRepository.findAll();
}

public List findByName(String name) {
return rentalAgentRepository.findByName(name);
}

public List findByEmail(String email) {
return rentalAgentRepository.findByEmail(email);
}

public List findByMobile(String mobile) {
return rentalAgentRepository.findByMobile(mobile);
}
}
< /code>
Служба переворота и критерий Агента < /p>
package za.co.property365.service;

import za.co.property365.domain.RentalAgent;

import java.util.List;

/**
* IRentallService.java
* ToDo: Methods declarations for - save, read, delete
*/

public interface IRentalAgentService {
RentalAgent save(RentalAgent rentalAgent);
RentalAgent findById(Long id);
void deleteById(Long id);
List findAll();
List findByName(String name);
List findByEmail(String email);
List findByMobile(String mobile);
}
< /code>
valueobject domain: < /p>
package za.co.property365.domain;

public interface ValueObject {

}
< /code>
helper: < /p>
package za.co.property365.util;

import org.apache.commons.validator.routines.EmailValidator;

import java.util.UUID;

public class Helper {
public static String generateId() {
return UUID.randomUUID().toString();
}

public static boolean isNullOrEmpty(String str) {
return str == null || str.isEmpty();
}

public static boolean isValidPostalCode(int postalCode) {
return postalCode >= 1000 && postalCode 0;
}

public static boolean isValidEmail(String email) {
if (isNullOrEmpty(email)) return false;
return EmailValidator.getInstance().isValid(email);
}

public static boolean isValidMobile(String mobile) {

if (isNullOrEmpty(mobile)) return false;
return mobile.matches("0[6-8][0-9]{8}");
}
}


Подробнее здесь: https://stackoverflow.com/questions/796 ... spring-boo
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»