第12章—使用NoSQL数据库—使用MongoDB+Jpa操作数据库

使用MongoDB+Jpa操作数据库

SpringData还提供了对多种NoSQL数据库的支持,包括MongoDB;neo4j和redis.他不仅支持自动化的repository,还支持基于模板的数据访问和映射注解.下面是一个Spring通过Jpa操作MongoDB数据库的小Demo:

数据的结构如图所示:

mog.gif

相关代码如下:

StuController:

import com.demo.jpamongodb.dao.StudentRepository;
import com.demo.jpamongodb.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;
@RestController
public class StuController {
    @Autowired
    private StudentRepository studentRepository;
    @RequestMapping("/getStuByName/{name}")
    public Optional<Student> getSchool1() {
        Optional<Student> stu = studentRepository.findById(1L);
        return stu;
    }
}

SchoolReponsitory

package com.demo.jpamongodb.dao;
import com.demo.jpamongodb.entity.School;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface SchoolReponsitory extends MongoRepository<School,Long> {
    School findSchoolByName(String name);
}

StudentRepository

import com.demo.jpamongodb.entity.Student;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface StudentRepository extends MongoRepository<Student, Long> {
    Student findByName(String name);
}

School

package com.demo.jpamongodb.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.net.Proxy;

@Document
public class School {
    @Id
    private Long id;

    private String name;
    private String address;

    public School() {
    }

    public School(Long id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

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

    @Override
    public String toString() {
        return "School{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

Student

package com.demo.jpamongodb.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;


//@AllArgsConstructor
//@Data
//@ToString
@Document
public class Student {
    @Id
    private Long id;

    private String name;
    private Integer age;
    private School shool;

    public Student() {
    }

    public Student(Long id, String name, Integer age, School shool) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.shool = shool;
    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public School getShool() {
        return shool;
    }

    public void setShool(School shool) {
        this.shool = shool;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", shool=" + shool +
                '}';
    }
}

application.properties

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=test
spring.data.mongodb.username=test
spring.data.mongodb.password=123456

server.port=8787

JpaMongodbApplicationTests

package com.demo.jpamongodb;
import com.demo.jpamongodb.dao.SchoolReponsitory;
import com.demo.jpamongodb.dao.StudentRepository;
import com.demo.jpamongodb.entity.School;
import com.demo.jpamongodb.entity.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class JpaMongodbApplicationTests {

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private SchoolReponsitory schoolReponsitory;


    @Test
    public void contextLoads() {
    }

    /**
     * 第一次单元测试
     * - student实体没有加home属性
     *
     * @throws Exception
     */
    @Test
    public void insertStudentWithoutHome() throws Exception {
        School school1 = schoolReponsitory.findSchoolByName("南京路中学");
        School school2 = schoolReponsitory.findSchoolByName("北京路中学");

        System.out.println(school1);
        System.out.println(school2);

//        schoolReponsitory.save(new  School(1L,"南京路中学","南京路"));

        studentRepository.save(new Student(1L, "小明", 30,school1));
//      studentRepository.save(new Student(2L, "小红", 40,school1));
//      studentRepository.save(new Student(3L, "小王", 50,school2));
    }

    /**
     * 第二次单元测试
     * - student实体加home属性
     *
     * @throws Exception
     */
    @Test
    public void insertStudentWitHome() throws Exception {
        School school1 = schoolReponsitory.findSchoolByName("南京路中学");
        School school2 = schoolReponsitory.findSchoolByName("北京路中学");

//      studentRepository.save(new Student(4L, "tom", 30,school1,"1小区"));
//      studentRepository.save(new Student(5L, "peter", 40,school1,"2小区"));
//      studentRepository.save(new Student(6L, "joy", 50,school2,"3小区"));
    }

    /**
     * 对查询结果打印
     */
    @Test
    public void findAll() {
        List<Student> students = studentRepository.findAll();
        students.forEach(student -> {
            System.out.println(student);
        });
    }

//    @Test
//    public void insertSchool(){
//        School school1 = School.builder().address("南京路").name("南京路中学").id(1L).build();
//        School school2 = School.builder().address("北京路").name("北京路中学").id(2L).build();

//new School(1L,"南京路中学","南京路");
//
//        schoolReponsitory.save(new  School(1L,"南京路中学","南京路"));
//        schoolReponsitory.save(school2);
//
//        School school = schoolReponsitory.findSchoolByName("南京路中学");
//        System.out.println(school);
//    }
}

pom.xml:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.beacon</groupId>
    <artifactId>jpa-mongodb</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!--数据库组件-->
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-data-jpa</artifactId>-->
        <!--</dependency>-->
        <!--数据库组件-->
        <!--<dependency>-->
            <!--<groupId>mysql</groupId>-->
            <!--<artifactId>mysql-connector-java</artifactId>-->
        <!--</dependency>-->
        <!--<dependency>-->
            <!--<groupId>com.alibaba</groupId>-->
            <!--<artifactId>druid</artifactId>-->
            <!--<version>1.1.10</version>-->
        <!--</dependency>-->
        <!--//添加AOP-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!-- Spring boot 引用Thymeleaf模板依赖包(Thymeleaf模板如果不适用,这里也可以不添加这段配置,Thymeleaf模板使用在下面会讲到) -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--mongodb-->
        <!--<dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongodb-driver</artifactId>
            <version>3.6.4</version>
        </dependency>-->


        <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.8.0</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.22</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

演示效果为:(注意我们需要先往MongoDB中添加数据)

xiao.gif

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏算法修养

PAT 1040

字符串APPAPT中包含了两个单词“PAT”,其中第一个PAT是第2位(P),第4位(A),第6位(T);第二个PAT是第3位(P),第4位(A),第6位(T)...

3497
来自专栏数据结构与算法

BZOJ3671: [Noi2014]随机数生成器(贪心)

第1行包含5个整数,依次为 x_0,a,b,c,d ,描述小H采用的随机数生成算法所需的随机种子。第2行包含三个整数 N,M,Q ,表示小H希望生成一个1到 N...

842
来自专栏李蔚蓬的专栏

Java基础知识的全面巩固_note1(附各种demo code)

上面的cmd中,javac程序是一个Java编译器,它将文件Welcome.java编译成Welcome.class.java程序启动Java虚拟机。虚拟机执行...

942
来自专栏深度学习与计算机视觉

算法-调整数组顺组使奇数位于偶数前面

题目: 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,偶数位于数组的后半部分。 解题思路: 比如我们有一个这样...

2067
来自专栏软件开发 -- 分享 互助 成长

C++ string类的学习

string类对于处理字符串的一些应用非常的方便,我个人感觉,string和字符数组const char *很像,而且又比字符数组用起来方便的多。 注意其删除,...

4329
来自专栏鸿的学习笔记

简单定义Python和Scala的类和对象

在现代编程语言里,类和对象都是绕不过的话题。对象这个概念可以是生活的抽象,为了更好的理解使用书来做比喻,每一本书都是一个对象,也就是一个实例,书本身具有的页码等...

821
来自专栏GreenLeaves

C# 装箱和拆箱

C#的值类型可以分为在栈上分配内存的值类型和在托管堆上分配内存的引用类型。 1、那么值类型和引用类型能否相互转换呢? 答案是肯定的,C#通过装箱和拆箱来实现两者...

19810
来自专栏有趣的django

第二章、深入类和对象

2190
来自专栏Coding迪斯尼

java开发编译器:把C语言的循环指令编译成java字节码

1953
来自专栏猿人谷

获取对象属性类型、属性名称、属性值的研究:反射和JEXL解析引擎

先简单介绍下反射的概念:java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动...

1.3K5

扫码关注云+社区

领取腾讯云代金券