【问题标题】:JPA ManyToMany returns nothingJPA 多对多不返回任何内容
【发布时间】:2019-09-02 11:11:05
【问题描述】:

我尝试使用 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);
    }

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

【问题讨论】:

  • 添加Getter和setter,也试试调试
  • 我有 getter 和 setter,我只是觉得在这里复制它们没什么用。我试过了,在发送列表之前它是空的
  • 检查注释@JoinTable中的表名,你应该把你的表的名字和@JoinColumn的名字一样
  • @kelgwiin 是同名

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


【解决方案1】:

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

@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的回答。

【讨论】:

  • 向我们展示您是如何创建列表的。看起来您正在构建一个空列表。确认您是否与此类似: List list = new ArrayList(); itemRepository.findAll().forEach(e -> list.add(e));返回列表;
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2019-10-23
    • 1970-01-01
    • 2013-08-02
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2019-04-06
    • 2012-02-15
    相关资源
    最近更新 更多