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è)置配置實(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;
    }
}

三:實(shí)體類配置

@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 持久化之前自動(dòng)設(shè)置
     * @param deleteFlag
     */
    public void setDeleteFlag(DeleteEnum deleteFlag) {
        this.deleteFlag = deleteFlag.value();
    }

    public Date getCreateDate() {
        return createDate;
    }

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

    public Date getUpdateDate() {
        return updateDate;
    }

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

    /**
     * 使用MongoDB Java Drive時(shí)用到
     * 等到Morphia支持事務(wù)時(shí)重構(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ù)操作說(shuō)明
     * 由于morphia還沒(méi)有原生的事務(wù)支持(請(qǐng)看morphia包下的README.md)
     * 所以需要用到mongoClient
     * 請(qǐng)不要在非事務(wù)的情況下使用
     * 相關(guān)操作參考鏈接如下
     * https://docs.mongodb.com/v4.0/core/transactions/
     * https://docs.mongodb.com/manual/core/transactions/
     */
//    以下三個(gè)字段是為事務(wù)操作準(zhǔn)備的,請(qǐng)不要濫用
    @Value("${mongodb.db}")
    private String dbName;
    @Value("${mongodb.collection}")
    private String dbCollectionName;
    @Value("${mongodb.uri}")
    private String mongodbUri;

    // 導(dǎo)入的 T 的類的類型,通過(guò)構(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;
    }

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

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


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

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

        // 按照要求分頁(yè)
        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();
    }

    /**
     * 實(shí)現(xiàn)分頁(yè)邏輯
     * @param pageNumber     需要查詢第幾頁(yè)
     * @param pageSize       每頁(yè)包含多少條記錄
     * @param queryCondition 查詢對(duì)象
     * @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ù)操作請(qǐng)參閱其他文檔
//此處是插入多條數(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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容