第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

转载于:https://www.cnblogs.com/charlypage/p/9445101.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值