Возврат неправильных значений с использованием JPA - PullRequest
0 голосов
/ 06 апреля 2020

Я относительно новичок в этом. Поэтому я постараюсь быть полным и лаконичным. Используя Eclipse и JPA, я пытаюсь установить связь между напитками и ликерами sh. Кажется, я сохраняю объекты в базе данных, но не могу получить нужные объекты. Все, что я смог найти, указывает на то, что у меня правильный формат. Поэтому я не уверен, почему я получаю этот результат, когда я запускаю тест

java .lang.AssertionError: Ожидаемый: итерируемый над [,] в любом порядке, но: нет совпадений элементов:, в []

Это мой соответствующий тест. Я смог сохранить и загрузить из базы данных из других тестов.


package com.example.mixeddrinkapp;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertThat;

import java.util.Optional;

import javax.annotation.Resource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@DataJpaTest
public class JPAMappingTest {

    @Resource
    private TestEntityManager entityManager;

    @Resource
    private DrinkRepository drinkRepo;

    @Resource
    private LiquorRepository liquorRepo;
    @Test
    public void shouldEstablishDrinktoLiquorRelationship() {
        Liquor liquor = liquorRepo.save(new Liquor("liquor", true));
        Liquor anotherLiquor = liquorRepo.save(new Liquor("anotherLiquor", true));

        Drink drink = new Drink("name", liquor.getId(), anotherLiquor.getId(), null, null, null, null, null, null, null);
        drink = drinkRepo.save(drink);
        Long drinkId = drink.getId();

        entityManager.flush();
        entityManager.clear();

        Optional<Drink> result = drinkRepo.findById(drinkId);
        drink = result.get();

        assertThat(drink.getLiquors(), containsInAnyOrder(liquor, anotherLiquor));
    }

Это мой класс питья

    package com.example.mixeddrinkapp;

import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Drink {

    @Id
    @GeneratedValue
    private Long drinkId;

    private String drinkName;

    private Long liquor1;

    private Long liquor2;

    private Long liquor3;

    private Long mixer1;

    private Long mixer2;

    private Long mixer3;

    private Long garnish1;

    private Long garnish2;

    private Long garnish3;

    @ManyToMany
    private Collection<Liquor> liquors;

    public Collection<Liquor> getLiquors() {

        return liquors;
    }

    public void setLiquors(Collection<Liquor> liquors) {
        this.liquors = liquors;
    }

    // default constructor
    public Drink() {
    }

    public Drink(String drinkName, Long liquor1, Long liquor2, Long liquor3, Long mixer1, Long mixer2, Long mixer3,
            Long garnish1, Long garnish2, Long garnish3) {
        this.drinkName = drinkName;
        this.liquor1 = liquor1;
        this.liquor2 = liquor2;
        this.liquor3 = liquor3;
        this.mixer1 = mixer1;
        this.mixer2 = mixer2;
        this.mixer3 = mixer3;
        this.garnish1 = garnish1;
        this.garnish2 = garnish2;
        this.garnish3 = garnish3;
    }

    public long getId() {
        return drinkId;
    }

    public String getName() {
        return drinkName;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (int) (drinkId ^ (drinkId >>> 32));
        result = prime * result + ((drinkName == null) ? 0 : drinkName.hashCode());
        result = prime * result + (int) (garnish1 ^ (garnish1 >>> 32));
        result = prime * result + (int) (garnish2 ^ (garnish2 >>> 32));
        result = prime * result + (int) (garnish3 ^ (garnish3 >>> 32));
        result = prime * result + (int) (liquor1 ^ (liquor1 >>> 32));
        result = prime * result + (int) (liquor2 ^ (liquor2 >>> 32));
        result = prime * result + (int) (liquor3 ^ (liquor3 >>> 32));
        result = prime * result + ((liquors == null) ? 0 : liquors.hashCode());
        result = prime * result + (int) (mixer1 ^ (mixer1 >>> 32));
        result = prime * result + (int) (mixer2 ^ (mixer2 >>> 32));
        result = prime * result + (int) (mixer3 ^ (mixer3 >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Drink other = (Drink) obj;
        if (drinkId != other.drinkId)
            return false;
        if (drinkName == null) {
            if (other.drinkName != null)
                return false;
        } else if (!drinkName.equals(other.drinkName))
            return false;
        if (garnish1 != other.garnish1)
            return false;
        if (garnish2 != other.garnish2)
            return false;
        if (garnish3 != other.garnish3)
            return false;
        if (liquor1 != other.liquor1)
            return false;
        if (liquor2 != other.liquor2)
            return false;
        if (liquor3 != other.liquor3)
            return false;
        if (liquors == null) {
            if (other.liquors != null)
                return false;
        } else if (!liquors.equals(other.liquors))
            return false;
        if (mixer1 != other.mixer1)
            return false;
        if (mixer2 != other.mixer2)
            return false;
        if (mixer3 != other.mixer3)
            return false;
        return true;
    }

Это мой класс ликера.

package com.example.mixeddrinkapp;

import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Liquor {

    @Id
    @GeneratedValue
    private Long liquorId;

    private String name;
    private boolean inStock;

    @ManyToMany(mappedBy = "liquors")
    private Collection<Drink> drinks;



    public Collection<Drink> getDrinks() {
        return drinks;
    }

    public void setDrinks(Collection<Drink> drinks) {
        this.drinks = drinks;
    }

    // default constructor
    public Liquor() {
    }

    public Liquor(String name, boolean inStock) {
        this.name = name;
        this.inStock = inStock;
    }

    public String getName() {

        return name;
    }

    public boolean getInStock() {

        return inStock;
    }

    public Long getId() {

        return liquorId;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((drinks == null) ? 0 : drinks.hashCode());
        result = prime * result + (inStock ? 1231 : 1237);
        result = prime * result + ((liquorId == null) ? 0 : liquorId.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Liquor other = (Liquor) obj;
        if (drinks == null) {
            if (other.drinks != null)
                return false;
        } else if (!drinks.equals(other.drinks))
            return false;
        if (inStock != other.inStock)
            return false;
        if (liquorId == null) {
            if (other.liquorId != null)
                return false;
        } else if (!liquorId.equals(other.liquorId))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

}
...