第12章—使用NoSQL数据库—使用MongoDB+Jpa操作数据库-阿里云开发者社区

开发者社区> 浅色夏墨> 正文

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

简介: 使用MongoDB+Jpa操作数据库 SpringData还提供了对多种NoSQL数据库的支持,包括MongoDB;neo4j和redis.他不仅支持自动化的repository,还支持基于模板的数据访问和映射注解.
+关注继续查看

使用MongoDB+Jpa操作数据库

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

数据的结构如图所示:

img_b96c8b02a2811d931dbe6cd47648c92e.gif
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中添加数据)

img_b3b54206fa4a3bca5124f34d0e53e2ea.gif
xiao.gif

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
使用 Math 类操作数据
使用 Math 类操作数据 Math 类位于 java.lang 包中,包含用于执行基本数学运算的方法, Math 类的所有方法都是静态方法,所以使用该类中的方法时,可以直接使用类名.
573 0
使用mybatis对数据库执行更新操作时,parameterType为某个具体的bean,而bean中传入的参数为null时,抛出异常
使用mybatis对数据库执行更新操作时,parameterType为某个具体的bean,而bean中传入的参数为null时,抛出异常 问题描述 在使用mybatis对数据库执行更新操作时,parameterType为某个具体的bean,而bean中传入的参数为null时,抛出异常如下:org.
1662 0
把ElasticSearch当成是NoSQL数据库
Elasticsearch 可以被当成一个 "NoSQL"-数据库来使用么? NoSQL 意味着在不同的环境下存在不同的东西, 而erestingly 它并不是真的跟 SQL 有啥关系. 我们开始只会觉得 "可能"而已, 所以细细研究了 Elasticsearch 的各种属性,包括它已经为了成就最具灵活性,可伸缩性和性能优异的分析查询引擎的那些属性。
1208 0
python3使用Lxml库操作XPath
download address: http://pypi.python.org/pypi/lxml/2.3 lxml is a Pythonic, mature binding for the libxml2 and libxslt libraries.
854 0
+关注
76
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载