java - 如何在JSP窗体中插入外键存入数据库?

标签 java mysql hibernate spring-mvc

这是一个 spring mvc 应用程序,这是其中的一部分。当我在表单中插入 category id 时,它让我遇到了这个错误:

Image

但是当我从表单中删除 category id 输入时,数据插入到数据库中。

产品.java

@Entity
@Table(name = "product", catalog = "flowershop")
public class Product implements java.io.Serializable {

private Integer id;
private Category categoryid;
private String name;
private Double price;

public Product() {
}

public Product(Category categoryid, String name, Double price) {
    this.categoryid = categoryid;
    this.name = name;
    this.price = price;
}

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

public void setId(Integer id) {
    this.id = id;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "categoryid",foreignKey = @ForeignKey(name = "Product_categoryid_productid"))
public Category getCategoryid() {
    return this.categoryid;
}

public void setCategoryid(Category categoryid) {
    this.categoryid = categoryid;
}

@Column(name = "name", length = 45)
public String getName() {
    return this.name;
}
public void setName(String name) {
    this.name = name;
}

@Column(name = "price", precision = 22, scale = 0)
public Double getPrice() {
    return this.price;
}
public void setPrice(Double price) {
    this.price = price;
}
}

分类.java

@Entity
@Table(name="category", catalog="flowershop")
public class Category  implements java.io.Serializable {


 private Integer id;
 private String name;
 private Set<Product> products = new HashSet<Product>(0);

public Category() {
}
public Category(String name, Set<Product> products) {
   this.name = name;
   this.products = products;
}

@Id @GeneratedValue(strategy=IDENTITY)
@Column(name="id", unique=true, nullable=false)
public Integer getId() {
    return this.id;
}
public void setId(Integer id) {
    this.id = id;
}

@Column(name="name", length=45)
public String getName() {
    return this.name;
}
public void setName(String name) {
    this.name = name;
}

@OneToMany(fetch=FetchType.LAZY, mappedBy="categoryid")
public Set<Product> getProducts() {
    return this.products;
}
public void setProducts(Set<Product> products) {
    this.products = products;
}

}

ProductDAOImp.java

@Repository("productDAO")
public class ProductDAOImp implements ProductDAO {

@Autowired
private SessionFactory sessionFactory;

@Override
public void newProduct(Product product) {

    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    session.save(product);
    tx.commit();
    session.close();
}

ProductServiceImp.java

@Service("productService")
@Transactional
public class ProductServiceImp implements ProductService {

@Override
public void newProduct(Product product) {

    productDAO.newProduct(product);
}
}

ProductController.java

@Controller
@Transactional
@RequestMapping("/product")
public class ProductController {

@Autowired
private CategoryService categoryService;

@Autowired
private ProductService productService;

@RequestMapping(value = "category/{id}", method = RequestMethod.GET)
public String category(@PathVariable("id") Integer id, ModelMap modelMap) {

    Category category = categoryService.find(id);
    Hibernate.initialize(category.getProducts());

    modelMap.put("products", category.getProducts());
    return "product.category";
}

@RequestMapping(value = {"newProduct"}, method = RequestMethod.GET)
public String newProduct(ModelMap modelMap) {

    Product product = new Product();

    modelMap.put("newProduct", product);
    modelMap.put("title", "New Product");
    return "product.newProduct";
}

@RequestMapping(value = {"newProduct"}, method = RequestMethod.POST)
public String newProduct(
        @ModelAttribute("newProduct") Product product,
        ModelMap modelMap) {

    modelMap.put("newProduct", product);

    try {

        productService.newProduct(product);
        return "product.newProduct";
    } catch (Exception e) {

        return "product.newProduct";
    }
}
}

新产品.jsp

<f:form method="POST" modelAttribute="newProduct" action="${pageContext.request.contextPath}/product/newProduct.html">
            <div class="form_row">
                <label class="contact"><strong>Name: </strong></label>
                <input name="name" type="text" class="contact_input"/>
            </div>
            <div class="form_row">
                <label class="contact"><strong>Price: </strong></label> 
                <input name="price" type="text" class="contact_input"/>
            </div>

            <div class="form_row">
                <label class="contact"><strong>Category Id: </strong></label>
                <input name="categoryid" type="text" class="contact_input"/>
            </div>
            <div class="form_row">
                <input type="submit" class="register" value="register">
            </div>
</f:form>

最佳答案

此注释 @GeneratedValue(strategy = IDENTITY) 会自动为记录分配一个 id。所以在你的项目中你希望使用手动生成的 id,请删除它。

关于java - 如何在JSP窗体中插入外键存入数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54723049/

相关文章:

spring - 如何获取存储在默认模式表中的租户标识符?

java - 如何在 AWS Lambda 运行时查看实际的 java 依赖项/库

java - 我在实现 "Active FTP server"时遇到问题

java - 获取 map 中的最后一个值

java - 使用 Apache LDAP API 从 Activedirector 检索当前密码

java - Hibernate 模型的部分更新

java - Hibernate 关系加载

MySQL 内连接查询需要很长时间

php mysql 二叉树计算

sql - 是否可以在 MySQL 中有索引 View ?