gpt4 book ai didi

java - 如何使用 Spring MVC 和 hibernate 连接/绑定(bind)两个表

转载 作者:行者123 更新时间:2023-12-01 19:34:59 27 4
gpt4 key购买 nike

我的英语不是很好,很抱歉有错误。

我正在使用 Spring、Spring MVC、Hibernate、Spring Data。

我有两个实体 Customer 和 CustomerDetails 我想连接/绑定(bind)它们。我正在使用 @OneToOne 注释,但我不知道如何为 CusomerDetails 设置客户,反之亦然。我发现我应该在 Controller 中创建 Customer 和 CustomerDetails ,然后连接它们,但它不起作用,我认为这是一个不好的方法。有人知道它应该是什么样子吗?

感谢您的帮助。

客户类别:

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="customer")
public class Customer {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="customer_id")
private int id;

@Column(name="name")
private String name;

@Column(name="email")
private String email;

@Column(name="address")
private String address;

@OneToOne(cascade=CascadeType.ALL)
private CustomerDetails customerDetails;

public Customer() {
}

public Customer(CustomerDetails customerDetails)
{
this.customerDetails=customerDetails;
}

public int getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}



public CustomerDetails getCustomerDetails() {
return customerDetails;
}

public void setCustomerDetails(CustomerDetails customerDetails) {
this.customerDetails = customerDetails;
}

@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", email=" + email + ", address=" + address
+ ", customerDetails=" + customerDetails + "]";
}

}

客户详细信息:


import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="customer_details")
public class CustomerDetails {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

@Column(name="surname")
private String lastName;

@Column(name="number")
private int number;

@OneToOne(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
private Customer customer;




public CustomerDetails() {

}


public int getId() {
return id;
}

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

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getNumber() {
return number;
}

public void setNumber(int number) {
this.number = number;
}

public Customer getCustomer() {
return customer;
}

public void setCustomer(Customer customer) {
this.customer = customer;
}

@Override
public String toString() {
return "CustomerDetails [id=" + id + ", lastName=" + lastName + ", number=" + number + ", customer=" + customer
+ "]";
}


}

服务:

import java.util.List;

import com.firstapp.entity.Customer;

public interface CustomerService {

public List<Customer>getCustomers();

public Customer getCustomer(int id);

public void saveCustomer(Customer customer);

public void deleteCustomer(int id);

public List<Customer>search(String keyword);

}


public interface CustomerDetailsService {

public List<CustomerDetails> getCustomers();

public CustomerDetails getCustomer(int id);

public void saveCustomer(CustomerDetails customer);

public void deleteCustomer(int id);
}


@Service
public class CustomerServiceImpl implements CustomerService {

@Autowired
private CustomerRepository repo;

public List<Customer> getCustomers() {
return repo.findAll();
}

public Customer getCustomer(int id) {
Optional<Customer>result= repo.findById(id);
return result.get();
}

public void saveCustomer(Customer customer) {
repo.save(customer);
}

public void deleteCustomer(int id) {
repo.deleteById(id);
}

public List<Customer>search(String keyword)
{
return repo.search(keyword);
}


}



import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.firstapp.entity.CustomerDetails;
import com.firstapp.repository.CustomerDetailsRepository;

@Service
public class CustomerDetailsServiceImpl implements CustomerDetailsService{

@Autowired
private CustomerDetailsRepository repo;

public List<CustomerDetails> getCustomers() {
return repo.findAll();
}

public CustomerDetails getCustomer(int id) {
return repo.findById(id).get();
}

public void saveCustomer(CustomerDetails customer) {
repo.save(customer);
}

public void deleteCustomer(int id) {
repo.deleteById(id);
}
}

存储库:

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.firstapp.entity.Customer;

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {

@Query(value="SELECT c from Customer c where c.name LIKE '%'|| :keyword || '%'"
+ "OR c.email LIKE '%'|| :keyword || '%'"
+ "OR c.address LIKE '%'|| :keyword || '%'")
public List<Customer>search(@Param("keyword")String keyword);
}


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.firstapp.entity.CustomerDetails;

@Repository
public interface CustomerDetailsRepository extends JpaRepository<CustomerDetails, Integer> {

}

我的 Controller :

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.firstapp.entity.Customer;
import com.firstapp.entity.CustomerDetails;
import com.firstapp.service.CustomerDetailsService;
import com.firstapp.service.CustomerDetailsServiceImpl;
import com.firstapp.service.CustomerService;
import com.firstapp.service.CustomerServiceImpl;

@Controller
@RequestMapping("/customer")public class CustomerController {

@Autowired
private CustomerService service;

@Autowired
private CustomerDetailsService serviceCD;

@GetMapping("/home")public String home(Model model)
{
List<Customer>customers=service.getCustomers();
model.addAttribute("message","Hello from Spring MVC"); model.addAttribute("customers",customers);
return "home-page";
}

@GetMapping("/showForm")
public String showForm(Map<String,Object>model)
{
Customer customer=new Customer();
CustomerDetails cd=new CustomerDetails();
customer.setCustomerDetails(cd);
model.put("customer",new Customer());
model.put("customerDetails", cd);
return "new-customer";
}

@PostMapping("/add")
public String addCustomer(@ModelAttribute("customer") Customer customer)
{
service.saveCustomer(customer);
return "redirect:/customer/addDetails";
}

@RequestMapping("/addDetails")
public String addCustomerDetails(@ModelAttribute("customerDetails") CustomerDetails customerDt)
{
serviceCD.saveCustomer(customerDt);
return "redirect:/customer/home";
}



@GetMapping("/edit")
public String editCustomer(@RequestParam int id, Model model)
{
Customer customer=service.getCustomer(id);
model.addAttribute("customer",customer);
return "edit-customer";
}

@GetMapping("/delete")
public String deleteCustomer(@RequestParam int id)
{
service.deleteCustomer(id);
return "redirect:/customer/home";
}

@GetMapping("/search")
public String search(@RequestParam String keyword,Model model)
{
List<Customer>customers=service.search(keyword);
model.addAttribute("customers",customers);
return "search-page";
}
}

我的jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Customer registration</title>

</head>
<body>

<div align="center">
<h2>New Customer</h2>

<form:form action="add" method="post" modelAttribute="customer">
<table>

<tr>
<td>Name:</td>
<td><form:input path="name"/></td>
</tr>

<tr>
<td>E-mail:</td>
<td><form:input path="email"/></td>
</tr>

<tr>
<td>Address:</td>
<td><form:input path="address"/></td>
</tr>

<tr>
<td></td><td><input type="submit" value="Submit"/></td>
</tr>


</table>

</form:form>

</div>

</body>


</html>

最佳答案

设置客户的客户详细信息:

customer.setCustomerDetail(customerDetail);
customerDetail.setCustomer(customer);

够了。 Spring JPA 自动设置表实体之间的引用和 id。

另外尝试更改模型层:

1) 首先您应该更改什么 - 将带有表名称的 mappedBy 参数添加到“@OneToOne”中2)使用@JoinColumn作为实体之一:

对于客户:

@OneToOne(mappedBy = "customer")
@JoinColumn(name = "customer_details_id", referencedColumnName = "id")

客户详细信息:

@OneToOne(mappedBy = "customer_detail")

另外:尝试在创建后、保存 Customer 之前将 CustomerDetail 实体保存到表中。

PS从技术上讲,无论您在哪里创建实体,它都只是模式和 SOLID 原则。@OneToOne 和 @JoinColumn 中的所有参数都应命名为实体中的字段和表。有一次我花了很长时间才解决这个问题。所以要准确。

关于java - 如何使用 Spring MVC 和 hibernate 连接/绑定(bind)两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59230313/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com