(Hibernate)无法添加具有多对多关系的实体

时间:2016-04-15 00:04:31

标签: spring hibernate jpa spring-boot entity

基本上,我的目标是让产品和工厂实体的关系是多对多的。 工厂必须有一些产品,而产品不必与工厂相关联。问题是,当我尝试添加产品实体时,我收到此错误。

Caused by: org.hsqldb.HsqlException: integrity constraint violation: NOT NULL check constraint; SYS_CT_10103 table: PRODUCT column: FACT_ID

这是我的Application类。 我希望能够将产品保存到存储库而不提供工厂列表但是我收到了错误,所以我尝试添加注释中的内容但仍然存在相同的错误。< / p>

@SpringBootApplication
public class Application implements CommandLineRunner {

    @Autowired
    private ProductRepo prodRepo;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    @Transactional
    public void run(String... strings) throws Exception {
    Product one = new Product();
  /*
    List<Product> productList= new ArrayList<Product>();
    productList.add(one);

    SomeFactory factory_one = new SomeaFactory("one", productList);
    List<Factory> factoryList = new ArrayList<Factory>();
    factoryList.add(factory_one);

    one.setFactoryList(factoryList);
  */
    prodRepo.save(one);
}

Product.java

@Entity
@Table(name="PRODUCT")
public class Product {
    private int id;
    private List<Factory> factoryList = null;

    public Product() {}

    @Id
    @Column(name = "PROD_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int getId()                  { return id; }
    public void setId(int id)           { this.id = id; }

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "productList", targetEntity = Factory.class)
    public List<Factory> getFactoryList() {
        return factoryList;
    }
    public void setFactoryList(List<Factory> f) {
        this.factoryList = f;
    }

}

SomeFactory.java

@Entity
@Table(name ="SOME_FACT")
public class SomeFactory extends Factory {
    private String name;
    private List<Product> productList;

    public SomeFactory() {}
    public SomeFactory(String name, List<Product> products) {
        this.name = name;
        this.productList = products;
    }

    @Column(name = "FACT_NAME", nullable = false)
    public String getName()             { return name; }
    public void setName(String name)    { this.name = name; }

    @ManyToMany
    @JoinTable(name = "PRODUCT",
            joinColumns = @JoinColumn(name = "FACT_ID", nullable = true),
            inverseJoinColumns = @JoinColumn(name = "PROD_ID", nullable = false))
    public List<Product> getProductList() {
        return productList;
    }
    public void setProductList(List<Product> products) {
        this.productList = products;
    }
}

Factory.java

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Factory {
    int id;

    public Factory() {}

    @Id
    @Column(name="FACT_ID")
    @GeneratedValue(strategy = GenerationType.TABLE)
    int getId()                     { return id; }
    void setId(int id)              { this.id = id; }
}

0 个答案:

没有答案