JPA ManyToMany不返回任何内容

时间:2019-04-11 18:16:29

标签: java spring spring-boot jpa many-to-many

我尝试使用JPA开发spring服务器,但在使用多对多关系时遇到了麻烦。这些是我的实体:

@Entity
public class Item {

    @Id
    private Integer id;
    private String name;
    private Float price;
    private Integer weight;


    @ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
    @JoinTable(name="itemingredient",
            joinColumns = @JoinColumn(name="iditem"),
            inverseJoinColumns = @JoinColumn(name="idingredient"))
    private List<Ingredient> ingredients=new ArrayList<>();

    public Item( String name, Float price, Integer weight, Ingredient... ingredients) {
        //this.id = id;
        this.name = name;
        this.price = price;
        this.weight = weight;
        this.ingredients = Stream.of(ingredients).collect(Collectors.toList());
        this.ingredients.forEach(x->x.getItems().add(this));
    }

    public Item() {

    }

@Entity
public class Ingredient {

    @Id
    private Integer id;
    private String name;
    private Float proteins;
    private Float lipids;
    private Float carbohydrates;
    private Float energeticValue;

    @ManyToMany(mappedBy = "ingredients")
    @JsonIgnore
    private List<Item> items=new ArrayList<>();

    public Ingredient(String name, Float proteins, Float lipids, Float carbohydrates, Float energeticValue) {
        //this.id = id;
        this.name = name;
        this.proteins = proteins;
        this.lipids = lipids;
        this.carbohydrates = carbohydrates;
        this.energeticValue = energeticValue;
    }

    public Ingredient(){

    }

我已经创建了存储库和其余的控制器。我正在为数据库使用mysql。我已经创建了表,并且已经有了用于关系的“ itemingredient”表。这是我的JPA配置:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "Repository")
public class JPAConfig {

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean em
                = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan("model");

        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(additionalProperties());

        return em;
    }

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/nha");
        dataSource.setUsername( "root" );
        dataSource.setPassword( "1234" );
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager(
            EntityManagerFactory emf){
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);

        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
        return new PersistenceExceptionTranslationPostProcessor();
    }

    Properties additionalProperties() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        properties.setProperty(
                "hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
        return properties;
    }
}

这是我的休息控制器:

@RestController
@RequestMapping(path="/items")
public class ItemController {
    @Autowired
    private ItemService itemService;

    @RequestMapping(value = "/all",method= RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<Item>> findAll(){
        return new ResponseEntity<>(itemService.findAll(),null, HttpStatus.OK);
    }

启动服务器并尝试获取所有项目后,服务器会发回一个空列表。我没有正确连接数据库吗?谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用对象映射器。如下所示:

@RequestMapping("/all")
public @ResponseBody String getitemsJSON() {
    ObjectMapper objectMapper = new ObjectMapper();
    //Set pretty printing of json
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    List<Item> itemlist = null;
    @SuppressWarnings("unused")
    String exception = null;
    String arrayToJson = null;
    try {
        itemlist = itemService.findAll();
        arrayToJson = objectMapper.writeValueAsString(itemlist );
    } catch (Exception ex) {
        ex.printStackTrace();
        exception = ex.getMessage();
    }
    return arrayToJson;
}

这是我对another SO thread的回答。

答案 1 :(得分:0)

我已经解决了。问题是我没有在@ComponentScan中写“ Repository”,而只是在@EnableJpaRepository中写了。我不知道我必须在那儿写。感谢您的帮助!