Morphia入門

Morphia官網(wǎng)

開發(fā)環(huán)境

  1. Jetbrain IDEA
  2. Maven

一: maven依賴

官方依賴

<dependency>
    <groupId>dev.morphia.morphia<groupId>
    <artifactId>core</artifactId>
    <version>1.5.3</version>
</dependency>

二: 入門設(shè)置

@Service(value = "morphiaDatastore")
public class MorphiaDatastore {
    @Value("${mongodb.db}")
    private String dbName;     //mongodb.uri=mongodb://${mongodb.username}:${mongodb.password} @${mongodb.ip}:${mongodb.port}/${mongodb.db}?authSource=admin
    @Value("${mongodb.uri}")
    private String mongodbUri;

    private Morphia morphia;
    private Datastore datastore;
    private MongoClient mongoClient;

    private void init() {
        if (morphia != null && datastore != null && mongoClient != null) {
            return;
        }
        morphia = new Morphia();
//        設(shè)置配置實體的包
        morphia.mapPackage("project.morphia.domain");

        MongoClientURI mongoClientURI = new MongoClientURI(mongodbUri);
        mongoClient = new MongoClient(mongoClientURI);
        datastore = morphia.createDatastore(mongoClient, dbName);
        datastore.ensureIndexes();
    }

    @Bean
    public Datastore getDatastoreInstance() {
        this.init();
        return datastore;
    }
}

三:實體類配置

@Entity("qs_answer")
public class MorphiaQsAnswerPO {
    @Id
    @Property("_id")
    private ObjectId id;
    @Property("question_id")
    private Long questionId;
    @Property("map")
    private Map<String, String> map;
    @Property("patient_id")
    private Long patientId;
    @Property("task_id")
    private Long taskId;
    private Long version;
    @Property("delete_flag")
    private Integer deleteFlag;
    @Property("create_date")
    private Date createDate;
    @Property("update_date")
    private Date updateDate;

    @PrePersist
    private void prePersist() {
        deleteFlag = deleteFlag == null ? DeleteEnum.NOT.value() : deleteFlag;
        createDate = createDate == null ? new Date() : createDate;
        updateDate = new Date();
    }

    public ObjectId getId() {
        return id;
    }

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

    public Long getQuestionId() {
        return questionId;
    }

    public void setQuestionId(Long questionId) {
        this.questionId = questionId;
    }

    public Map<String, String> getMap() {
        return map;
    }

    public void setMap(Map<String, String> map) {
        this.map = map;
    }

    public Long getPatientId() {
        return patientId;
    }

    public void setPatientId(Long patientId) {
        this.patientId = patientId;
    }

    public Long getTaskId() {
        return taskId;
    }

    public void setTaskId(Long taskId) {
        this.taskId = taskId;
    }

    public Long getVersion() {
        return version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public DeleteEnum getDeleteFlag() {
        return DeleteEnum.get(deleteFlag);
    }

    /**
     * @see MorphiaQsAnswerPO#prePersist 持久化之前自動設(shè)置
     * @param deleteFlag
     */
    public void setDeleteFlag(DeleteEnum deleteFlag) {
        this.deleteFlag = deleteFlag.value();
    }

    public Date getCreateDate() {
        return createDate;
    }

    /**
     * @see MorphiaQsAnswerPO#prePersist 持久化之前自動設(shè)置
     * @param createDate
     */
    @Deprecated
    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getUpdateDate() {
        return updateDate;
    }

    /**
     * @see MorphiaQsAnswerPO#prePersist 持久化之前自動設(shè)置
     * @param updateDate
     */
    @Deprecated
    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }

    /**
     * 使用MongoDB Java Drive時用到
     * 等到Morphia支持事務(wù)時重構(gòu)這部分
     */
    @SuppressWarnings("all")
    public Document toDocument() {
        Document document = new Document();
        document.put("_id", id);
        document.put("question_id", questionId);
        document.put("map", map);
        document.put("patient_id", patientId);
        document.put("task_id", taskId);
        document.put("version", version);
        document.put("delete_flag", deleteFlag);
        document.put("create_date", createDate);
        document.put("update_date", updateDate);
        for (Iterator<Map.Entry<String, Object>> it = document.entrySet().iterator(); it.hasNext(); ) {
            Map.Entry<String, Object> entry = it.next();
            if (entry.getValue() == null) {
                it.remove();
            }
        }
        return document;
    }
}

四:增刪改查demo

public class MorphiaBaseImpl {
    @Resource
    private Datastore datastore;

    /**
     * 事務(wù)操作說明
     * 由于morphia還沒有原生的事務(wù)支持(請看morphia包下的README.md)
     * 所以需要用到mongoClient
     * 請不要在非事務(wù)的情況下使用
     * 相關(guān)操作參考鏈接如下
     * https://docs.mongodb.com/v4.0/core/transactions/
     * https://docs.mongodb.com/manual/core/transactions/
     */
//    以下三個字段是為事務(wù)操作準(zhǔn)備的林螃,請不要濫用
    @Value("${mongodb.db}")
    private String dbName;
    @Value("${mongodb.collection}")
    private String dbCollectionName;
    @Value("${mongodb.uri}")
    private String mongodbUri;

    // 導(dǎo)入的 T 的類的類型,通過構(gòu)造類裝載
    private Class<T> clazz;

    @SuppressWarnings("unchecked")
    public MorphiaBaseImpl() {
        this.clazz = (Class<T>) ((ParameterizedType) super.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    public T save(T po) {
        datastore.save(po);
        return po;
    }

    /**
     * 對于morphia的merge操作
     * po的id為null會報MappingException
     * 找不到匹配的id會報UpdateException
     * @param po 需要持久化的實體類
     * @return 持久化后的類
     */
    public T update(T po) {
        datastore.merge(po);
        return po;
    }

    /**
     * 根據(jù)id找到數(shù)據(jù)
     * @param id 實體類的主鍵 id 需要是ObjectId類型
     * @return null if not found
     */
    public T get(Serializable id) {
        return datastore.createQuery(clazz).field("id").equal(id).first();
    }


    /**
     * @param pageNumber 需要查詢第幾頁
     * @param pageSize   每頁包含多少條記錄
     */
    public Page<T> findAll(int pageNumber, int pageSize) {
 

        // Morphia  創(chuàng)建查詢
        Query<T> query = datastore.createQuery(clazz);

        // 按照要求分頁
        return query.find(new FindOptions()
                .skip(pageNumber > 0 ? ((pageNumber - 1) * pageSize) : 0)
                .limit(pageSize))
                .toList();
    }

    public Page<T> findByAND(int pageNumber, int pageSize, MorphiaQueryCondition queryCondition) {

        Query<T> query = datastore.createQuery(clazz);
        //按照條件獲取查詢結(jié)果
        if (null != queryCondition){
            query = queryCondition.andCriteria(query);
        }

        return query.find(new FindOptions()
                .skip(pageNumber > 0 ?((pageNumber-1)*pageSize) : 0)
                .limit(pageSize))
                .toList();
    }

    /**
     * 實現(xiàn)分頁邏輯
     * @param pageNumber     需要查詢第幾頁
     * @param pageSize       每頁包含多少條記錄
     * @param queryCondition 查詢對象
     * @return
     */
    public Page<T> findByOR(int pageNumber, int pageSize, MorphiaQueryCondition queryCondition) {
        Query<T> query = datastore.createQuery(clazz);
        //按照條件獲取查詢結(jié)果
        if (null != queryCondition){
            query = queryCondition.orCriteria(query);
        }
        // 查詢總記錄數(shù)
        Long totalCount = query.count();
        
        retutn query.find(new FindOptions()
                .skip(pageNumber > 0 ?((pageNumber-1)*pageSize) : 0)
                .limit(pageSize))
                .toList();
    }

    /**
     * 將PO轉(zhuǎn)到mongodb原生的Document
     * @return
     */
    private List<Document> posToDocuments(List<T> pos) {
        List<Document> list = new ArrayList<>();
        for (T po : pos) {
            Document document = po.toDocument();
            list.add(document);
        }
        return list;
    }

//mongodb的事務(wù)操作請參閱其他文檔
//此處是插入多條數(shù)據(jù)亦渗,使用了原子性的操作insertMany
    public void saveList(List<T> pos) throws MongoException {
        final MongoClient client = MongoClients.create(mongodbUri);

        MongoCollection<Document> collection = client.getDatabase(dbName).getCollection(dbCollectionName);
        List<Document> documents = posToDocuments(pos);
        collection.insertMany(documents, new InsertManyOptions());
    }

//此處更新列表不是事務(wù)操作,事務(wù)操作需要在MongoDB建立replica set
    public List<T> updateListWithoutTransaction(List<T> pos, Boolean bool) throws MongoException {
        ArrayList<T> errorList = new ArrayList<>();
        for (T po : pos) {
            try {
                update(po);
            } catch (Exception e) {
                errorList.add(po);
            }
        }
        return errorList;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末削茁,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌侮东,老刑警劉巖粱年,帶你破解...
    沈念sama閱讀 222,807評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件售滤,死亡現(xiàn)場離奇詭異,居然都是意外死亡台诗,警方通過查閱死者的電腦和手機完箩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來拉庶,“玉大人嗜憔,你說我怎么就攤上這事∈险蹋” “怎么了吉捶?”我有些...
    開封第一講書人閱讀 169,589評論 0 363
  • 文/不壞的土叔 我叫張陵,是天一觀的道長皆尔。 經(jīng)常有香客問我呐舔,道長,這世上最難降的妖魔是什么慷蠕? 我笑而不...
    開封第一講書人閱讀 60,188評論 1 300
  • 正文 為了忘掉前任珊拼,我火速辦了婚禮,結(jié)果婚禮上流炕,老公的妹妹穿的比我還像新娘澎现。我一直安慰自己仅胞,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 69,185評論 6 398
  • 文/花漫 我一把揭開白布剑辫。 她就那樣靜靜地躺著干旧,像睡著了一般。 火紅的嫁衣襯著肌膚如雪妹蔽。 梳的紋絲不亂的頭發(fā)上椎眯,一...
    開封第一講書人閱讀 52,785評論 1 314
  • 那天,我揣著相機與錄音胳岂,去河邊找鬼编整。 笑死,一個胖子當(dāng)著我的面吹牛乳丰,可吹牛的內(nèi)容都是我干的掌测。 我是一名探鬼主播,決...
    沈念sama閱讀 41,220評論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼成艘,長吁一口氣:“原來是場噩夢啊……” “哼赏半!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起淆两,我...
    開封第一講書人閱讀 40,167評論 0 277
  • 序言:老撾萬榮一對情侶失蹤断箫,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后秋冰,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體仲义,經(jīng)...
    沈念sama閱讀 46,698評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,767評論 3 343
  • 正文 我和宋清朗相戀三年剑勾,在試婚紗的時候發(fā)現(xiàn)自己被綠了埃撵。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,912評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡虽另,死狀恐怖暂刘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情捂刺,我是刑警寧澤谣拣,帶...
    沈念sama閱讀 36,572評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站族展,受9級特大地震影響森缠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜仪缸,卻給世界環(huán)境...
    茶點故事閱讀 42,254評論 3 336
  • 文/蒙蒙 一贵涵、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦宾茂、人聲如沸瓷马。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽决采。三九已至,卻和暖如春坟奥,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背拇厢。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評論 1 274
  • 我被黑心中介騙來泰國打工爱谁, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人孝偎。 一個月前我還...
    沈念sama閱讀 49,359評論 3 379
  • 正文 我出身青樓访敌,卻偏偏與公主長得像,于是被迫代替她去往敵國和親衣盾。 傳聞我的和親對象是個殘疾皇子寺旺,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,922評論 2 361

推薦閱讀更多精彩內(nèi)容