SpringData MongoDB 入门案例

SpringData MongoDB 入门案例

创建工程,引入坐标


    <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
    </dependencies>

创建配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation="http://www.springframework.org/schema/context
          https://www.springframework.org/schema/context/spring-context.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
          http://www.springframework.org/schema/beans
          https://www.springframework.org/schema/beans/spring-beans.xsd">



    <!--包扫描-->
    <context:component-scan base-package="com.topcheer" />
    <mongo:repositories base-package="com.topcheer"/>

    <context:property-placeholder location="db.properties" />
    <mongo:mongo-client host="47.110.91.230" port="27017" id="mongoClient" credentials="test:123456@test">
            <mongo:client-options connections-per-host="8"
                                  threads-allowed-to-block-for-connection-multiplier="4"
                                  connect-timeout="1000"
                                  max-wait-time="1500"
                                  write-concern="SAFE"
                                  socket-keep-alive="true"
                                  socket-timeout="1500"/>
    </mongo:mongo-client>
    <mongo:db-factory dbname="test" mongo-ref="mongoClient" id="mongoDbFactory"/>


    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>

</beans>

创建实体类

//使用@Document建立的是实体类和collection的关系
@Document(collection = "article")
public class Article {

    @Id//用来标识主键
    private Integer id;

    //使用@Field建立实体类中属性跟collection中字段的映射关系,如果省略,代表两个名称一致
    //@Field
    private String name;
    private String content;
    private Integer hits;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Integer getHits() {
        return hits;
    }

    public void setHits(Integer hits) {
        this.hits = hits;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", content='" + content + '\'' +
                ", hits=" + hits +
                '}';
    }
}

自定义 dao接口


public interface ArticleDao extends MongoRepository<Article, Integer> {

    //根据标题查询
    List<Article> findByNameLike(String name);

    //根据点击量查询
    List<Article> findByHitsGreaterThan(Integer hits);

}

测试方法:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-mgo2.xml")
public class ArticleDaoTest {

    @Autowired
    private ArticleDao articleDao;


    //保存
    @Test
    public void testSave() {
        Article article = new Article();
        article.setId(1);
        article.setName("dalianpai");
        article.setContent("dalianpai123");
        article.setHits(100);

        articleDao.save(article);
    }


    //修改
    @Test
    public void testUpdate() {
        Article article = new Article();
        article.setId(1);
        article.setName("dalianpai2");
        article.setContent("dalianpai2123");
        article.setHits(200);

        articleDao.save(article);
    }

    //修改
    @Test
    public void testDelete() {
        articleDao.deleteById(1);
    }


    //做数据
    @Test
    public void makeData() {
        for (int i = 1; i <= 10; i++) {
            Article article = new Article();
            article.setId(i);
            article.setName("dalianpai" + i);
            article.setContent("dalianpai" + i);
            article.setHits(100 + i);

            articleDao.save(article);
        }
    }


    //查询所有
    @Test
    public void testFindAll() {
        List<Article> articles = articleDao.findAll();
        for (Article article : articles) {
            System.out.println(article);
        }
    }

    //主键查询
    @Test
    public void testFindById() {
        Optional<Article> opt = articleDao.findById(1);
        System.out.println(opt.get());
    }

    //分页和排序
    @Test
    public void testFindAllWithPageAndSort() {

        //设置排序条件
        Sort sort = Sort.by(Sort.Order.desc("hits"));

        //设置分页条件
        Pageable pageable = PageRequest.of(1, 3, sort);

        Page<Article> page = articleDao.findAll(pageable);
        for (Article article : page.getContent()) {
            System.out.println(article);
        }
    }


    //根据标题查询
    @Test
    public void testFindByName() {
        List<Article> articles = articleDao.findByNameLike("dalianpai1");
        for (Article article : articles) {
            System.out.println(article);
        }
    }

    //根据标题查询
    @Test
    public void testFindByHitsGreaterThan() {
        List<Article> articles = articleDao.findByHitsGreaterThan(105);
        for (Article article : articles) {
            System.out.println(article);
        }
    }


}

image-20201012162612443

image-20201012162634671

posted @ 2020-10-12 16:29  天宇轩-王  阅读(147)  评论(0编辑  收藏  举报