gpt4 book ai didi

hibernate - Spring Boot + Hibernate 一对一映射

转载 作者:行者123 更新时间:2023-12-01 02:32:47 25 4
gpt4 key购买 nike

我需要一个关于使用一对一映射对两个表进行 CRUD 操作的示例

hibernate 。

我想了解这是如何在 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>

///////////////////////persons//////////////////////

   <!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>

///////////////////////人物表演/////////////////////////////

    <!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>

最佳答案

例如,您有一个实体 PersonPersonDetail,它们将有一个 @OneToOne 映射。这意味着一个人有一个 PersonDetail。在 Person 实体中,您必须将映射设置为 PersonDetail

我强烈建议您阅读 hibernate 和 spring-data 的文档。还有映射的 java 文档。您只会通过逐步学习这些东西来了解一切是如何协同工作的。

我为您提供了一个小的工作示例。让您的应用程序基于此代码示例运行。

个人实体:

@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}}

关于hibernate - Spring Boot + Hibernate 一对一映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39389482/

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