<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    paulwong

    為SPRING DATA MONGODB REPOSITORY添加自定義方法

    自從用了SPRING DATA MONGODB后,增刪改查的實現方法都不用自己寫了,只需聲明方法名稱,SPRING會自動添加代碼,但用時候SPRING自帶的方法不夠,難免要添加的,因此如何在原有的方法上疊加自定義的方法呢?

    定義自定義的接口
    public interface VideoRepositoryCustom {
        
        public List<Cat1UpdateCount> getVideoWithUpdateFrag(List<String> importantCat1List);

    }


    添加自定義的實現
    import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
    import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
    import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
    import static org.springframework.data.mongodb.core.aggregation.Aggregation.project;
    import static org.springframework.data.mongodb.core.aggregation.Aggregation.unwind;

    import java.util.Date;
    import java.util.List;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.mongodb.core.MongoTemplate;
    import org.springframework.data.mongodb.core.aggregation.Aggregation;
    import org.springframework.data.mongodb.core.aggregation.AggregationResults;
    import org.springframework.data.mongodb.core.query.Criteria;

    import program.video.aggregation.valueobject.Cat1UpdateCount;
    import program.video.valueobject.Video;

    public class VideoRepositoryImpl implements VideoRepositoryCustom{
        
        private static Logger logger = LoggerFactory.getLogger(VideoRepositoryImpl.class);
        
        @Autowired
        private MongoTemplate mongoTemplate;
        

        public List<Cat1UpdateCount> getVideoWithUpdateFrag(List<String> importantCat1List) {
            
            logger.info(new Date().toString());
            
            /**
             * db.videos.aggregate(
                [
                   { $match: { "frags.isnew" : true } },
                   { $unwind: "$frags" },
                   { $match: { "frags.isnew" : true } },
                   { $group: { 
                               _id: {cat1:"$cat1"},
                               count: { $sum: 1 },
                               publishdate2: { $max: "$publishdate"}
                             }
                   }
                   
                ]
                )
             
    */
            Aggregation agg = newAggregation(
                    project("frags","cat1","publishdate"),
                    match(
                            Criteria.where("frags.isnew").is(Boolean.TRUE)
                            .and("cat1").in(importantCat1List)
                         ),
                    unwind("frags"),//展開子項LIST,且是內鏈接,即如果父和子的關聯ID沒有的就不會輸出
                    match(Criteria.where("frags.isnew").is(Boolean.TRUE)),
                    group("cat1")//設置分組字段
                        .count().as("updateCount")//增加COUNT為分組字段
                        .last("publishdate").as("publishDate"),//增加publishDate為分組字段
                    project("publishDate","cat1","updateCount")//重新挑選字段
                        .and("cat1").previousOperation()//為前一操作所產生的ID FIELD建立別名
                );

                AggregationResults<Cat1UpdateCount> results = mongoTemplate.aggregate(agg, Video.COLLECTION_NAME, Cat1UpdateCount.class);
                List<Cat1UpdateCount> cat1UpdateCountList = results.getMappedResults();
            
            return null;
        }

    }


    原先的接口實現多重繼承
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.mongodb.repository.Query;
    import org.springframework.data.repository.PagingAndSortingRepository;
    import org.springframework.data.repository.query.Param;

    import program.video.valueobject.Video;


    public interface VideoRepository extends PagingAndSortingRepository<Video, String>,VideoRepositoryCustom {

        @Query("{ title : {$regex : ?0 } }")
        public Page<Video> findVideosByKeyword(@Param("title") String keyword, Pageable page);
        
        @Query("{ pid : ?0 }") 
        public Video findByVideoId(String id); 
        
        @Query(value="{ pid : ?0 , ver: { $gt : ?1 }}")
        public Video findByIdAndVersion(String id, int ver);
        
        
        public Page<Video> findByTitleLike(String title, Pageable pageable);
        
        @Query("{ title : {$regex : ?0}, cat1 : ?1}")
        public Page<Video> findVideosByTitleAndCat1(String title, String cat1, Pageable pageable);
        
        @Query("{ cat1 : ?0}")
        public Page<Video> findVideosByCat1(String cat1, Pageable pageable);
        
        @Query("{ title : {$regex : ?0}, cat1 : ?1, status : ?2}")
        public Page<Video> findVideosByTitleAndCat1AndStatus(String title, String cat1, int status, Pageable pageable);
        
        @Query("{ title : {$regex : ?0}, cat1 : ?1, status : { $in : [ ?2, null]}}")
        public Page<Video> findVideosByTitleAndCat1AndStatusExist(String title, String cat1, int status, Pageable pageable);
        
        @Query("{ title : {$regex : ?0}, status : ?1}")
        public Page<Video> findVideosByTitleAndStatus(String title, int status, Pageable pageable);
        
        @Query("{ title : {$regex : ?0}, status : { $in : [ ?1, null]}}")
        public Page<Video> findVideosByTitleAndStatusExist(String title, int status, Pageable pageable);
        
        @Query("{ cat1 : ?0, status : ?1}")
        public Page<Video> findVideosByCat1AndStatus(String cat1, int status, Pageable pageable);
        
        @Query("{ cat1 : ?0, status : { $in : [ ?1, null]}}")
        public Page<Video> findVideosByCat1AndStatusExist(String cat1, int status, Pageable pageable);
        
        @Query("{ status : ?0}")
        public Page<Video> findVideosByStatus(int status, Pageable pageable);
        
        @Query("{status : { $in : [ ?0, null]}}")
        public Page<Video> findVidesByStatusExist(int status, Pageable pageable);
    }


    SPRING DATA 配置文件
    <?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
              http://www.springframework.org/schema/context/spring-context-3.0.xsd
              http://www.springframework.org/schema/data/mongo
              http://www.springframework.org/schema/data/mongo/spring-mongo-1.3.xsd
              http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
    >


        <!-- To translate any MongoExceptions thrown in @Repository annotated classes -->
        <context:annotation-config />
        
        <context:property-placeholder location="classpath*:/properties/mongodb/mongo.properties"/>

        <!-- Default bean name is 'mongo' -->
        <mongo:mongo host="${mongo.host}" port="${mongo.port}">
            <mongo:options connections-per-host="${mongo.connectionsPerHost}"
                threads-allowed-to-block-for-connection-multiplier
    ="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
                connect-timeout
    ="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}"
                auto-connect-retry
    ="${mongo.autoConnectRetry}" socket-keep-alive="${mongo.socketKeepAlive}"
                socket-timeout
    ="${mongo.socketTimeout}" slave-ok="${mongo.slaveOk}"
                write-number
    ="1" write-timeout="0" write-fsync="true" />
        </mongo:mongo>

        <!-- <mongo:db-factory 
                            dbname="${mongo.dbname}" 
                            username="${mongo.username}"
                            password="${mongo.password}"
                            mongo-ref="mongo" /> 
    -->
                            
        <mongo:db-factory 
                            
    dbname="${mongo.dbname}" 
                            mongo-ref
    ="mongo" />

        <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
            <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
        </bean>
        
        <mongo:repositories base-package="com.tcl.project7.boss.**.repository" />

    </beans>


    注意的是,自定義的實現類要以IMPL后綴,則SPRING可以自動識別的,無需再指定了。

    調用REPOSITORY
    @Autowired
    private VideoRepository videoRepository;

    posted on 2013-12-24 09:23 paulwong 閱讀(2170) 評論(1)  編輯  收藏 所屬分類: SPRINGMONGODB

    Feedback

    # re: 為SPRING DATA MONGODB REPOSITORY添加自定義方法 2015-11-17 16:36 李大破

    寫的很清楚很詳細,謝謝啊  回復  更多評論   


    主站蜘蛛池模板: 四虎国产成人永久精品免费 | 久久九九AV免费精品| 久久亚洲精品成人av无码网站| 四虎精品视频在线永久免费观看| 亚洲免费福利在线视频| 亚洲国产精品尤物YW在线观看 | 成熟女人牲交片免费观看视频| 免费无码婬片aaa直播表情| 亚洲国产综合专区电影在线| 精品熟女少妇AV免费观看| 一级人做人a爰免费视频| 免费A级毛片无码A∨免费| 亚洲av无码专区国产不乱码| 亚洲国产精品一区二区第一页| 国产免费毛不卡片| 拍拍拍无挡免费视频网站| 亚洲一区精彩视频| 亚洲福利在线观看| 波多野结衣免费在线| 亚洲日韩乱码久久久久久| 91成年人免费视频| 国产人成网在线播放VA免费| 亚洲制服丝袜精品久久| 日本红怡院亚洲红怡院最新| 日本不卡视频免费| 黄页网站在线观看免费高清| 美女视频黄的免费视频网页| 亚洲精品视频在线观看视频| 久久精品国产亚洲Aⅴ香蕉| 91在线品视觉盛宴免费| 无码精品国产一区二区三区免费| 水蜜桃视频在线观看免费| 亚洲人成www在线播放| 亚洲电影中文字幕| 亚洲另类激情综合偷自拍图| 免费A级毛片无码A| 免费看的成人yellow视频| 99久久久国产精品免费无卡顿| 免费高清国产视频| 在线观看人成视频免费无遮挡| 美女被羞羞网站免费下载|