我需要一个关于两个表的CRUD操作的示例,使用
进行一对一映射休眠。
我想了解如何在Spring Boot中完成此操作。
我已经提到过[this] [1]
链接,但它只显示一个表。
如果有人有这样的链接到网站/ github,它将非常有用。
提前致谢
我的工作代码
/////////////////////////主要应用//////////////////// //////////
package com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
@SuppressWarnings("deprecation")
@SpringBootApplication
public class SpringBootWeb1Application extends SpringBootServletInitializer{
public static void main(String[] args) {
SpringApplication.run(SpringBootWeb1Application.class, args);
}
}
////////////////////////////////的IndexController ////////////// //////
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/")
String index(){
return "index";
}
}
//////////////////////// PersonController ///////////////////
package com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.model.Person;
import com.service.PersonService;
@Controller
public class PersonController {
@Autowired
private PersonService personService;
@Autowired
public void setPersonService(PersonService personService) {
this.personService = personService;
}
@RequestMapping(value = "/persons", method = RequestMethod.GET)
public String list(Model model){
model.addAttribute("persons", personService.listAllPersons());
return "persons";
}
@RequestMapping("person/{id}")
public String showPerson(@PathVariable Integer id, Model model){
model.addAttribute("person", personService.getPersonById(id));
return "personshow";
}
@RequestMapping("person/edit/{id}")
public String edit(@PathVariable Integer id, Model model){
model.addAttribute("person", personService.getPersonById(id));
return "personform";
}
@RequestMapping("person/new")
public String newPerson(Model model){
model.addAttribute("person", new Person());
return "personform";
}
@RequestMapping(value = "person", method = RequestMethod.POST)
public String saveProduct(Person person){
personService.savePerson(person);
return "redirect:/person/" + person.getId();
}
@RequestMapping("person/delete/{id}")
public String delete(@PathVariable Integer id){
personService.deletePerson(id);
/*return "redirect:/products";*/
return "personform";
}
}
/////////////////////////////////人///////////// /////////////
package com.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
///////////////////////////// PersonDetail ///////////////// ////////////
package com.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "PersonDetail", catalog = "myschema")
public class PersonDetail {
@Id
@GeneratedValue
private Integer id;
private String address;
private Integer age;
@OneToOne(fetch=FetchType.LAZY)
@PrimaryKeyJoinColumn
private Person person;
public PersonDetail(){}
public PersonDetail(Integer id,String address,Integer age)
{
this.id=id;
this.address=address;
this.age=age;
}
@GenericGenerator(name = "generator", strategy = "foreign")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "address", nullable = false, length = 20)
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Column(name = "age", nullable = false)
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
///////////////////////////// PersonRepository ///////////////// /////////////
package com.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.model.Person;
@Repository
public interface PersonRepository extends CrudRepository<Person, Integer>{
}
////////////////////////// PersonDetailRepository //////////////////// /
package com.repository;
import org.springframework.data.repository.CrudRepository;
import com.model.PersonDetail;
public interface PersonDetailRepository extends CrudRepository<PersonDetail, Integer>{
}
///////////////////////////////服务/////////////// ////////
package com.service;
import com.model.Person;
public interface PersonService {
Iterable<Person> listAllPersons();
Person getPersonById(Integer id);
Person savePerson(Person person);
void deletePerson(Integer id);
}
/////////////////////////////// ServiceImpl /////////////// //////
package com.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.model.Person;
import com.repository.PersonRepository;
@Service
public class PersonServiceImpl implements PersonService{
private PersonRepository personRepository;
@Autowired
public void setPersonRepository(PersonRepository personRepository) {
this.personRepository = personRepository;
}
@Override
public Iterable<Person> listAllPersons() {
// TODO Auto-generated method stub
return personRepository.findAll();
}
@Override
public Person getPersonById(Integer id) {
// TODO Auto-generated method stub
return personRepository.findOne(id);
}
@Override
public Person savePerson(Person person) {
// TODO Auto-generated method stub
return personRepository.save(person);
}
@Override
public void deletePerson(Integer id) {
personRepository.delete(id);
}
}
////////////////////////的index.jsp //////////////////// /////////
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Spring Boot Example</title>
<!-- <th:block th:include="fragments/headerinc :: head"></th:block> -->
</head>
<body>
<div class="container">
<div th:fragment="header">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#" th:href="@{/}">Home</a>
<ul class="nav navbar-nav">
<li><a href="#" th:href="@{/persons}">Persons</a></li>
<li><a href="#" th:href="@{/person/new}">Create Person</a></li>
</ul>
</div>
</div></nav></div>
<!-- <div class="container"> -->
<!-- <th:block th:include="fragments/header :: header"></th:block> -->
</div>
</body>
</html>
///////////////////////// personform.jsp /////////////////// ////////
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Spring Boot Example</title>
<th:block th:include="fragments/headerinc :: head"></th:block>
</head>
<body>
<div class="container">
<th:block th:include="fragments/header :: header"></th:block>
<h2>Person Details</h2>
<div>
<form class="form-horizontal" th:object="${person}" th:action="@{/person}" method="post">
<input type="hidden" th:field="*{id}"/>
<div class="form-group">
<label class="col-sm-2 control-label">Person Id:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{id}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{name}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Address:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{address}"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Age:</label>
<div class="col-sm-10">
<input type="text" class="form-control" th:field="*{age}"/>
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</div>
</div>
</body>
</html>
/////////////////////////人///////////////////// /
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Spring Boot Example</title>
<th:block th:include="fragments/headerinc :: head"></th:block>
</head>
<body>
<div class="container">
<!--/*/ <th:block th:include="fragments/header :: header"></th:block> /*/-->
<div th:if="${not #lists.isEmpty(persons)}">
<h2>Person List</h2>
<table class="table table-striped">
<tr>
<th>Id</th>
<th>Person Id</th>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>View</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr th:each="person : ${persons}">
<td th:text="${person.id}"><a href="/person/${id}">Id</a></td>
<td th:text="${person.id}">Person Id</td>
<td th:text="${person.name}">description</td>
<td th:text="${person.personDetail.address}">Address</td>
<td th:text="${person.personDetail.age}">Age</td>
<!-- <td th:text="${product.price}">price</td> -->
<td><a th:href="${ '/person/' + person.id}">View</a></td>
<td><a th:href="${'/person/edit/' + person.id}">Edit</a></td>
<td><a th:href="${'/person/delete/' + person.id}">Delete</a></td>
</tr>
</table>
</div>
</div>
</body>
</html>
////////////////////////// personshow //////////////////// /////////
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Person Details</title>
<th:block th:include="fragments/headerinc :: head"></th:block>
</head>
<body>
<div class="container">
<!--/*/ <th:block th:include="fragments/header :: header"></th:block> /*/-->
<h2>Person Details</h2>
<div>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">Person Id:</label>
<div class="col-sm-10">
<p class="form-control-static" th:text="${person.id}">Person Id</p></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<p class="form-control-static" th:text="${person.name}">name</p>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Address:</label>
<div class="col-sm-10">
<p class="form-control-static" th:text="${person.personDetail.address}">address</p>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Name:</label>
<div class="col-sm-10">
<p class="form-control-static" th:text="${person.personDetail.address}">age</p>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
答案 0 :(得分:7)
例如,您有一个实体Person
和PersonDetail
,它将具有@OneToOne
映射。这意味着一个人有一个PersonDetail。在Person
实体中,您必须将映射设置为PersonDetail
。
我真的建议您阅读hibernate和spring-data的文档。还有映射的java-docs。通过逐步学习这些东西,您将只了解一切如何协同工作。
我为你提供了一些工作实例。让您的应用程序在这个代码示例的基础上工作。
人员实体:
@Entity
public class Person {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
@OneToOne(cascade = CascadeType.ALL)
private PersonDetail personDetail;
//getter setter
@Override
public String toString() {
return "Person{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", personDetail=" + personDetail +
'}';
}
}
PersonDetail实体:
@Entity
public class PersonDetail {
@Id
@GeneratedValue
private Long id;
private String street;
private Integer postalCode;
@OneToOne
@PrimaryKeyJoinColumn
private Person person;
//getter setter
@Override
public String toString() {
return "PersonDetail{" +
"id=" + id +
", street='" + street + '\'' +
", postalCode=" + postalCode +
'}';
}
}
存储库:
public interface PersonRepository extends CrudRepository<Person, Long> {
}
public interface PersonDetailRepository extends CrudRepository<PersonDetail, Long> {
}
应用程序启动类:
@SpringBootApplication
public class SpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication .class, args);
}
@Component
class Dummy implements CommandLineRunner{
@Autowired
PersonRepository repo;
@Override
public void run(String... string) throws Exception {
Person person = new Person();
person.setFirstName("firstname");
person.setLastName("lastname");
PersonDetail personDetail = new PersonDetail();
personDetail.setStreet("Street");
person.setPersonDetail(personDetail);
repo.save(person);
repo.findAll().forEach(p -> System.out.println(p.toString()));
}
}
}
输出:
Person{id=1, firstName='firstname', lastName='lastname', personDetail=PersonDetail{id=1, street='Street', postalCode=null}}
答案 1 :(得分:1)
如果你想要单向 OneToOne映射,我就是这样做的。
我有一个这样的模型:有一些项目的请求,有人提出要约。我想知道哪一个是被选中的(没有双关语;))。所以,这两个类都是:
Request.java
@Entity
public class Request {
// id and other columns...
@JoinColumn(name = "chosen_offer")
@OneToOne
private Offer chosenOffer = null;
// constructors, getters, setters, etc.
}
Offer.java
@Entity
public class Offer {
// id and other columns...
// nothing special here
// constructors, getters, setters, etc.
}
这是我的SupplyRequests表的样子(使用MySQL WorkBench):