簡體   English   中英

Spring Boot + Hibernate一對一映射

[英]Spring Boot + Hibernate One To One Mapping

我需要一個關於兩個表上的CRUD操作的示例,使用一對一映射

休眠。

我想了解如何在Spring Boot中完成此操作。

我已經提到了[這] [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>

例如,您有一個實體PersonPersonDetail ,它將具有@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}}

如果您想要單向 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):

請求MySQL表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM