提问者:小点点

Spring Data Thymeleaf-无法插入相关记录,外键为空


我有2个具有一对多关系的实体。由于外键为空,相关子条目无法插入。不过在测试中有效。

看起来高低不一,大多数都解决了,因为提问者没有把孩子加到父母身上,这不是我的情况。任何帮助都很感激!

错误

由以下原因引起:java. sql.SQLIntegrityConstraintViolationException:ORA-01400:无法将NULL插入("AIWA"."CAT_DT"."CAT_ID")

编辑1:在下方添加详细的错误日志。

2017-03-01 09:45:04 INFO AbstractBatchImpl:208-HHH000010:在批量发布时,它仍然包含JDBC语句2017-03-01 09:45:04 DEBUG JpaTransactionManager:898-提交异常后启动事务回滚

实体

public class Cat{
    private List<CatDt> catDts = new ArrayList<CatDt>();

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "cat", cascade=CascadeType.ALL)
    public List<CatDt> getCatDts() {
        if(this.catDts==null){
            this.catDts = new ArrayList<CatDt>();
        }
        return this.catDts;
    }

    public void setCatDts(List<CatDt> catDts) {
        this.catDts = catDts;
    }
}

public class CatDt{
    private Cat cat;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
    @JoinColumn(name = "CAT_ID", nullable = false)
    public Cat getCat() {
        return this.cat;
    }

    public void setCat(Cat cat) {
        this.cat = cat;
    }
}

胸腺叶形式

<ul th:each="item, stat: *{catDts}">
    <li>
        <span th:text="#{front.cat.CatDt.no.label}">No</span>
        <label th:text="${stat.count}">1</label>
    </li>
    <li>
        <span th:text="#{front.cat.CatDt.name.label}">Name</span>
        <input type="text" th:field="*{catDts[__${stat.index}__].name}" th:id="${'name-'+stat.index}">
    </li>
    <li>
        <span th:text="#{front.cat.CatDt.descr.label}">Description</span>
        <input type="text" th:field="*{catDts[__${stat.index}__].descr}" th:id="${'descr-'+stat.index}">
    </li>
    <li>
        <span th:text="#{front.cat.CatDt.lang.label}">Language</span>
        <input type="text" th:field="*{catDts[__${stat.index}__].language}" th:id="${'language-'+stat.index}">
    </li>       
</ul>

生成超文本标记语言形式

<form action="/aiwaweb/cat/create" method="post">
    <!-- Main info -->
    <ul>
        <li>
            <span>Code</span>
            <input id="code" name="code" value="" type="text">          
        </li>
        <li>
            <span>Type</span>
            <select id="catType" name="catType">
                <option...>...</option>
            </select>
        </li>
        <li>
            <span>Status</span>
            <select id="status" name="status">
                <option value="0">INACTIVE</option>
                <option value="1">ACTIVE</option>
            </select>
        </li>           
    </ul>

    <!-- Details -->    
    <ul>
        <li>
            <span>No.</span>
            <label>1</label>
        </li>
        <li>
            <span>Name</span>
            <input id="name-0" name="catDts[0].name" value="" type="text">
        </li>
        <li>
            <span>Description</span>
            <input id="descr-0" name="catDts[0].descr" value="" type="text">
        </li>
        <li>
            <span>Language</span>
            <input id="language-0" name="catDts[0].language" value="" type="text">
        </li>
    </ul>
</form>

编辑2更新了控制器create()以将Cat添加到CatDt(之前它只是将catDt添加到Cat);希望这种双向关系链接能够解决,但没有。

控制器

@GetMapping({"/create"})
public String create(ModelMap model){
    Cat cat = new Cat();
    List<CatDt> catDts = new ArrayList<CatDt>();
    CatDt catDt = new CatDt();
    catDt.setCat(cat); //this is the extra line added
    catDts.add(catDt);
    cat.setCatDts(catDts);
    model.addAttribute("cat", cat);
    return "cat/create";
}

@PostMapping(value="/create", params={"save"})
public String save(final Cat cat
        , final BindingResult bindingResult, final ModelMap model){
    if(bindingResult.hasErrors()){
        return "cat/create";
    }
    Cat updatedCat = catService.save(cat);
    model.clear();
    return "redirect:/cat/create";
}

到目前为止我所做的

  1. 当我在控制器save()上调试时,Cat在List中有孩子CatDt,但CatDt的cat属性为null;但仔细想想,也许它应该为null,因为Cat还没有保存,所以还没有Id。

单元测试

@Test
public void testCatSave(){
    Cat cat = new Cat();
    cat.setCode("11111");
    ...     
    //add cat details
    List<CatDt> catDts = new ArrayList<CatDt>();        
    CatDt catDt = new CatDt();
    catDt.setCat(cat);
    catDt.setName("Test");
    ...
    catDts.add(catDt);
    cat.setCatDts(catDts);          
    Cat catUpdated = catService.save(cat);
}

持久性配置

public class PersistenceConfig {
    @Autowired
    private Environment env;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory()
    {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setDataSource(dataSource());
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setJpaProperties(hibernateProperties());
        factory.setPackagesToScan("ae.tbits.atn.aiwacore.common.model");
        return factory;
    }

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

    @Bean
    public HibernateExceptionTranslator hibernateExceptionTranslator(){
        return new HibernateExceptionTranslator();
    }

    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        dataSource.setUrl(env.getProperty("jdbc.url"));
        dataSource.setUsername(env.getProperty("jdbc.username"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
env.getRequiredProperty("hibernate.type"));
        return properties;        
    }     
}

在T之后执行此操作,但不保存子记录http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#the-controller


共1个答案

匿名用户

好的,所以最后我能够解决。结果不知何故,孩子们的catDts没有被添加到cat对象中。

在控制器保存()中,我手动重新分配并保存。

public String save(final Cat cat
        , final BindingResult bindingResult, final ModelMap model){
    if(bindingResult.hasErrors()){
        logger.info("Binding result error in create(save)");
        return "cat/create";
    }
    //manually reassign - start
    List<CatDt> catDts = cat.getCatDts();
    for (CatDt catDt : catDts) {
        catDt.setCat(cat);
    }
    cat.setCatDts(catDts);
    //manually reassign - end

    Cat updatedCat = catService.save(cat); //saveAndFlush
    model.clear();
    return "redirect:/cat/create";

}

虽然这奏效了,但我认为不知何故我的胸腺叶形式没有正确设置,因此它没有链接,所以欢迎任何人提出解释。

谢谢。