为什么映射列表为空?

时间:2017-12-07 18:09:22

标签: java hibernate jpa

我是hibernate和jpa的新手。我需要一些帮助。我正在使用spring boot开发一个restful服务应用程序。使用mysql和hibernate。

当我打电话给我的服务“成分”阵列将是空的那样。 Empty array

在数据库成分表和配方表中有一对多关系所以我试图用JPA做同样的事情,但我找不到正确的方法。当我尝试获取食谱我可以访问但成分列表总是空的。

我的数据库设计: DB Design

配方实体:

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity()
@Table(name="recipe")
@Getter
@Setter
public class Recipe {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "recipe_id")
    private int recipeId;

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

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

    @Column(name = "picture_id")
    private int pictureId;

    @OneToMany(mappedBy = "recipe",fetch = FetchType.EAGER)
    private List<Ingredient> ingredients = new ArrayList<>();


}

成分实体:

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.io.Serializable;

@Entity()
@Table(name = "ingredient")
@Getter
@Setter
public class Ingredient implements Serializable{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ingredient_id")
    private int ingredientId;

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

    @ManyToOne
    @JoinColumn(name = "recipe_id",nullable = false)
    private Recipe recipe;

    @ManyToOne(cascade =  CascadeType.ALL)
    @JoinColumn(name = "material_id",nullable = false)
    private Material material;

}

RecipeDAO:

import com.mutfak.dolapservice.dao.interfaces.IRecipeDAO;
import com.mutfak.dolapservice.entity.Recipe;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Transactional
@Repository
public class RecipeDAO implements IRecipeDAO {

    @PersistenceContext
    private EntityManager entityManager;

    @SuppressWarnings("unchecked")
    @Override
    public List<Recipe> getRecipes() {
        String query = "FROM Recipe ORDER BY recipe_id";

        return (List<Recipe>) entityManager.createQuery(query).getResultList();
    }

    @Override
    public Recipe getRecipeByMaterial(int materialId) {
        return null;
    }

    @Override
    public Recipe getRecipeById(int id) {
        return null;
    }

    @Override
    public void addRecipe(Recipe recipe) {

    }

    @Override
    public void updateRecipe(Recipe recipe) {

    }

    @Override
    public void deleteRecipe(int id) {

    }
}

1 个答案:

答案 0 :(得分:0)

最后我找到了解决方案。 Lombok注释和JPA无法正常工作。 JPA无法获得List&lt;&gt;与龙目岛。