springboot整合jpa

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hkj</groupId>
    <artifactId>boot-jpa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>boot-jpa</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

yml配置

server:
  port: 8080
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&allowPublicKeyRetrieval=true
    username: root
    password: LJY19950703
    initialization-mode: never
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

model实体

package com.hkj.bootjpa.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.CascadeType;
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.Table;
import java.io.Serializable;

/**
 * @author liujy
 * @description Person实体
 * @since 2021-02-02 09:51
 */
@Getter
@Setter
@Entity
@Table(name = "person")
@org.hibernate.annotations.Table(appliesTo = "person", comment = "人员表")
@NoArgsConstructor
public class Person implements Serializable {
    private static final long serialVersionUID = 1832462648159684791L;
    @Id
    @GeneratedValue
    @Column(name = "id", nullable = false)
    private long id;
    @Column(name = "name", length = 20, nullable = false)
    private String name;
    @Column(name = "age", nullable = false)
    private int age;
    @Column(name = "sex", length = 10, nullable = false)
    private String sex;
    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JsonIgnore
    private Hobby hobby;
}

package com.hkj.bootjpa.model;

import com.fasterxml.jackson.annotation.JsonBackReference;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.io.Serializable;


/**
 * @author liujy
 * @description Hobby实体
 * @since 2021-02-02 09:51
 */
@Getter
@Setter
@Entity
@NoArgsConstructor
@Table(name = "hobby")
@org.hibernate.annotations.Table(appliesTo = "hobby", comment = "爱好表")
public class Hobby implements Serializable {
    private static final long serialVersionUID = 7547162962331614550L;
    @Id
    @GeneratedValue
    @Column(name = "id", nullable = false)
//    @Id
//    @GeneratedValue(generator = "uuid2")
//    @GenericGenerator(name = "uuid2", strategy = "uuid2")
//    @Column(columnDefinition = "BINARY(16)")
    private long id;
    @Column(name = "name", length = 20, nullable = false)
    private String name;
    @OneToOne(mappedBy = "hobby")
    private Person person;
}

repository

package com.hkj.bootjpa.repository;

import com.hkj.bootjpa.model.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author liujy
 * @description person repository
 * @since 2021-02-02 09:56
 */
@Repository
public interface PersonRepository extends JpaRepository<Person, Long> {
    List<Person> findByAge(int age);
}

service

package com.hkj.bootjpa.service;

import com.hkj.bootjpa.model.Person;
import com.hkj.bootjpa.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author liujy
 * @description person service
 * @since 2021-02-02 09:58
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class PersonService {
    @Autowired
    private PersonRepository personRepository;

    public void save(final Person model) {
        this.personRepository.save(model);
    }
}

controller

package com.hkj.bootjpa.controller;

import com.hkj.bootjpa.model.Person;
import com.hkj.bootjpa.repository.PersonRepository;
import com.hkj.bootjpa.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author liujy
 * @description controller
 * @since 2021-02-02 10:37
 */
@RestController
@Slf4j
@RequestMapping("/person/w")
public class PersonController {
    @Autowired
    private PersonService personService;
    @Autowired
    private PersonRepository personRepository;

    /**
     * @description 新建Person
     * @date2021/2/2 10:42
     */
    @PostMapping(value = "/add")
    public void add(@RequestBody Person person) {
        personService.save(person);
        log.info("{} instance {} was created.", Person.class.getSimpleName(), person.getName());
    }

    /**
     * @description 查询Person列表
     * @date 2021/2/2 10:42
     */
    @GetMapping(value = "/search")
    public List<Person> search() {
        List<Person> all = personRepository.findAll();
        return all;
    }

    /**
     * @description 测试
     * @date 2021/2/2 10:42
     */
    @GetMapping(value = "/t")
    public String test() {
        return "success";
    }
}

包结构如下:


包结构

推荐阅读更多精彩内容

  • 1添加依赖 <dependency> <groupId>org.springframework.boot</gro...
    清风_皓月阅读 30评论 0 0
  • JPA全称Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系...
    stellarxiong阅读 77评论 0 0
  • 前言 Jpa (Java Persistence API) 是 Sun 官方提出的 Java 持久化规范。它为 J...
    月弦阅读 101评论 0 0
  • 简介 我们都知道一个概念ORM(Object Relational Mapping)对象关系映射,ORM的作用是在...
    CodePandaes阅读 123评论 0 1
  • 1.先来看一下项目的目录结构 2.在整合之前我们要在pom.xml中添加上依赖 3.加上了必要的依赖后我们就要在a...
    麦角a阅读 48评论 0 0