<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 李大破

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


    主站蜘蛛池模板: 99久久久精品免费观看国产| 97亚洲熟妇自偷自拍另类图片| 亚洲国产成人久久77| 久久99国产综合精品免费| 亚洲AV无码成人精品区天堂| 精品一区二区三区免费| 久久精品九九亚洲精品天堂| 麻豆精品不卡国产免费看| 亚洲男人天堂2017| 99精品一区二区免费视频| 亚洲制服在线观看| 宅男666在线永久免费观看 | 久久久综合亚洲色一区二区三区| 在线观看免费无码专区| 亚洲码在线中文在线观看| 一本无码人妻在中文字幕免费 | 中文字幕在线亚洲精品 | 亚洲av无码久久忘忧草| 性xxxxx免费视频播放| 在线综合亚洲中文精品| 国产成人精品123区免费视频| 四虎影视永久在线精品免费| 久久久久一级精品亚洲国产成人综合AV区| 国产在线国偷精品免费看| 亚洲AV无码第一区二区三区| 成年人免费的视频| 国产成人高清亚洲一区久久 | 日韩亚洲产在线观看| 精品国产免费观看| 精品国产污污免费网站入口在线| 亚洲精品蜜桃久久久久久| 99在线精品视频观看免费| 男女男精品网站免费观看| 亚洲V无码一区二区三区四区观看| 亚洲精品视频在线观看免费| 亚洲熟女综合一区二区三区| 中文字幕日韩亚洲| 无码国产精品一区二区免费虚拟VR| 亚洲av成人中文无码专区| 国产亚洲真人做受在线观看| 一二三四影视在线看片免费|