spring JPA集成MongoDB

 mongodb作为nosql数据库的一种,在javaee开发中也越来越受到重视,这里介绍springboot+jpa+mongodb开发过程。

什么是MongoDB ?

MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数据库系统。

在高负载的情况下,添加更多的节点,可以保证服务器性能。

MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。

MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

1.新建maven工程,引入springboot和mongodb依赖。

maven配置如下:

<?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.2.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.momgo</groupId>
    <artifactId>mongo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Mongo</name>
    <description>Demo project for Spring Boot JPA + MongoDB</description>

    <properties>
        <java.version>12</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.8.0</version>
        </dependency>
    </dependencies>

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

</project>

2.添加数据库配置

spring:
  data:
    mongodb:
      host: localhost
      port: 27017
      database: user

3.添加实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document("user")
class User implements Serializable {

    private static final long serialVersionUID = -3896901585340927241L;

    @Id
    private Long id;
    private String name;
    private String password;
    private int age;
}

4.添加Repository接口,连接数据库

@Repository
public interface UserRepository extends MongoRepository<User,Long> {
}

5.添加Service接口

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User findOne(Long id){
        return userRepository.findById(id).get();
    }

    public User save(User user){
        return userRepository.save(user);
    }

    public List<User> findAll(){
        return userRepository.findAll();
    }
}

6.添加测试类

@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void find_all_test() {
        List<User> all = userService.findAll();
        System.out.println(all);
    }


    @Test
    public void save_test() {

        User user = new User();
        user.setId(1L);
        user.setName("user001");
        user.setAge(12);
        user.setPassword("password");
        User save = userService.save(user);
        System.out.println(save);
    }

}

如果你配置都对的话,应该测试是没有问题的。

有几点需要注意:

User实例类中:@Document("user")不能写成@Document(collation = "user"),否则查询的时候会报错:

org.springframework.data.mongodb.UncategorizedMongoDbException: Query failed with error code 2 and error message 'Field 'locale' is invalid in: { locale: "user" }' on server localhost:27017;

 

下面是我的测试记录: 

在数据库中也是能找到记录的:

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 点我我会动 设计师:上身试试 返回首页