"Mongodb" Morphia with spring in conjunction with the detailed

Source: Internet
Author: User
Tags mongoclient
Morphia Introduction

With the rise of internet web2.0 website, the traditional relational database in dealing with web2.0 website, especially the super large-scale and high concurrent SNS type web2.0 pure dynamic website already appeared to be powerless, exposed many insurmountable problems, but the relational database is very rapid development because of its own characteristic. The production of NoSQL database is to solve the challenge of multiple data types of large-scale data collection, especially the problem of large data application.
As a new representative of the NoSQL database, MongoDB has been used by many enterprises in the project. Morphia is an ORM framework based on NoSQL. Simplifies the persistence layer operation of the NoSQL. The following is a brief introduction to the use case of Morphia. Morphia Create Factory

public class Morphiafactorybean extends abstractfactorybean<morphia> {/** * packages to scan and map * * Private

    String[] mappackages;

    /** * to map the class * * private string[] mapclasses;

    /** * When scanning packets, whether to ignore the unmapped class * Here according to the original definition of Morphia, default set to False/private Boolean ignoreinvalidclasses;
    Public class<?> Getobjecttype () {return morphia.class;
        } protected Morphia CreateInstance () throws Exception {Morphia = new Morphia (); if (mappackages!= null) {for (String packagename:mappackages) {//We tell Morphia to find in the designated package
            Find all classes marked with @entity, and all the mapping metadata in the class Morphia.mappackage (PackageName, ignoreinvalidclasses); } if (mapclasses!= null) {for (String entityclass:mapclasses) {Morphia.
            Map (Class.forName (Entityclass));
    } return Morphia;
     } public string[] Getmappackages () {   return mappackages;
    } public void Setmappackages (string[] mappackages) {this.mappackages = mappackages;
    String[] Getmapclasses () {return mapclasses;
    } public void Setmapclasses (string[] mapclasses) {this.mapclasses = mapclasses;
    public Boolean isignoreinvalidclasses () {return ignoreinvalidclasses; } public void Setignoreinvalidclasses (Boolean ignoreinvalidclasses) {this.ignoreinvalidclasses = Ignoreinval
    idclasses; }
}
instance factory for MongoDB
public class Mongofactorybean extends Abstractfactorybean<mongo> {//representing the list of servers (master-slave or fragment) of the string array private Strin
    G[] serverstrings;

    The MongoDB configuration object uses the default configuration private mongoclientoptions mongoclientoptions = new Mongoclientoptions.builder (). build ();
    Public class<?> Getobjecttype () {return mongo.class; /** * Create Instance * @return * @throws Exception/protected Mongoclient CreateInstance () throws E
        xception {mongoclient mongoclient = null;
        Mongocredential credential = mongocredential.createcredential ("User", "mydb", "Password". ToCharArray ()); /*if (null!= mongoclientoptions) {mongoclient = new Mongoclient (Getserverlist (), Arrays.aslist (credential),
        Mongoclientoptions);
        else {mongoclient = new Mongoclient (Getserverlist (), Arrays.aslist (credential)); }*/if (null!= mongoclientoptions) {mongoclient = new Mongoclient (Getserverlist (), MONGOCLIEntoptions);
        }else{mongoclient = new Mongoclient (Getserverlist ());
    return mongoclient;
    String[] Getserverstrings () {return serverstrings;
    } public void Setserverstrings (string[] serverstrings) {this.serverstrings = serverstrings; /** * Parse out the list of server objects based on the list of server strings * @return * @throws Exception * @Title: Getserverlist/P Rivate list<serveraddress> getserverlist () throws Exception {list<serveraddress> serverlist = new ARR
        Aylist<serveraddress> ();
                try {for (String serverstring:serverstrings) {string[] temp = Serverstring.split (":");
                String host = temp[0]; if (Temp.length > 2) {throw new IllegalArgumentException ("Invalid Server address string:" + Serve
                rstring); else if (Temp.length = 2) {Serverlist.add (new ServerADdress (Host, Integer.parseint (temp[1)));
                else {serverlist.add (new ServerAddress (host));
        } return serverlist;
        catch (Exception e) {throw new Exception ("Error while converting serverstring to Serveraddresslist", e); }
    }
}

After the

Mongo instance and Morphia are configured, we will create the datastore.

public class Datastorefactorybean extends abstractfactorybean<datastore> {//Morphia instance, preferably single private morph

    IA Morphia;

    mongoclient example, preferably a single case private mongoclient mongoclient;

    Database name private String dbname;

    User name, can be empty private String username;

    Password, which can be null private String password;

    Whether to confirm that the index exists, default false private Boolean toensureindexes = false;

    Confirm Caps exists, default false private Boolean toensurecaps = false; @Override protected Datastore CreateInstance () throws Exception {datastore ds = Morphia.createdatastore (MONGO
        Client, dbname);
        if (toensureindexes) {ds.ensureindexes ();
        } if (toensurecaps) {ds.ensurecaps ();
    } return DS;
    Public Morphia Getmorphia () {return morphia;
    public void Setmorphia (Morphia morphia) {This.morphia = Morphia;
   Public Mongoclient getmongoclient () {return mongoclient; public void Setmongoclient (Mongoclient mongoclient) {this.mongoclient = mongoclient;
    Public String Getdbname () {return dbname;
    } public void Setdbname (String dbname) {this.dbname = dbname;
    Public String GetUserName () {return username;
    } public void Setusername (String username) {this.username = username;
    Public String GetPassword () {return password;
    } public void SetPassword (String password) {this.password = password;
    public Boolean istoensureindexes () {return toensureindexes;
    } public void Settoensureindexes (Boolean toensureindexes) {this.toensureindexes = toensureindexes;
    public Boolean istoensurecaps () {return toensurecaps;
    } public void Settoensurecaps (Boolean toensurecaps) {this.toensurecaps = Toensurecaps;
       @Override public class<?> Getobjecttype () { return datastore.class;
        @Override public void Afterpropertiesset () throws Exception {Super.afterpropertiesset ();
        if (mongoclient = = null) {throw new IllegalStateException ("Mongoclient is not set");
        } if (Morphia = = null) {throw new IllegalStateException ("Morphia is not set"); }
    }
}

Configuration file

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Xmlns:xs I= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "http://www.springframework.org/schema/be Ans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd "default-lazy-init=" true "> <!--make employment Factory Create MONGO instance--> <bean id= "mongoclient" class= "Com.test.mongo.MongoFactoryBean" > <!--Set server list, default to Loc alhost:27017--> <property name= "serverstrings" > <array> <value>1 27.0.0.1:27017</value> </array> </property> </bean> <!--use factory to create mor Phia instance, completing class mapping operations--> <bean id= "Morphia" class= "Com.test.mongo.MorphiaFactoryBean" > <!--Specify the Pojo to scan Package path--> <property name= "Mappackages" > <array> <value>com.test.mod
       El</value>     </array> </property> <!--Specify the class to map--> <!--<property name= "mapclasses "> <array> </array> </property>--> <!--Ignore classes that are not available when scanning packages. Default to False--> <property name= "ignoreinvalidclasses" value= "false"/> </bean> <!--using factory creation Datastore, while completing the index and caps confirmation operation--> <bean id= "datastore" class= "Com.test.mongo.DatastoreFactoryBean" > & Lt;property name= "Morphia" ref= "Morphia"/> <property name= "mongoclient" ref= "mongoclient"/> &L t;! --Collection name--> <property name= "dbname" value= "${mongo.server.dbname}"/> <!--username and password can be thought Empty--> <property name= "username" value= "${mongo.server.user}"/> <property name= "password" Valu E= "${mongo.server.pwd}"/> <!--to confirm the index and caps, the default is flase--> <property name= "Toensureinde Xes "value=" true "/&GT <property name= "Toensurecaps" value= "true"/> </bean> </beans>

Configure entity

@Entity (noclassnamestored = True) @Indexes (@Index ("Bookname,authorname")) public class Book {@Id private Objecti

    d ID;

    Private String BookName;

    Private String status;

    Private String AuthorName;

    Private String label;

    Private String description;

    Private String URL;
    Public ObjectId GetId () {return id;
    public void SetId (ObjectId id) {this.id = ID;
    Public String Getbookname () {return bookname;
    } public void Setbookname (String bookname) {this.bookname = BookName;
    Public String GetStatus () {return status;
    public void SetStatus (String status) {this.status = status;
    Public String Getauthorname () {return authorname;
    } public void Setauthorname (String authorname) {this.authorname = AuthorName;
    Public String Getlabel () {return label; public void SetLabel (String label) {thiS.label = label;
    Public String GetDescription () {return description;
    } public void SetDescription (String description) {this.description = description;
    Public String GetUrl () {return URL;
    public void SetUrl (String url) {this.url = URL;
 }
}

Configure DAO

@Component public
class Webpagedao extends Basicdao<book, objectid> {/

    /Instantiate the class when injected into Datastore
    // All additions and deletions are based on the Datastore method
    @Autowired public
    Webpagedao (datastore ds) {
        super (DS);
    }

    Public long Findbyinfo (string bookname, String authorname) {
        query<book> Query = Getdatastore (). CreateQuery ( Book.class)
                . Field ("BookName"). Equal (BookName).
                field ("AuthorName"). equal (AuthorName);
        return count (query);
    }

The above is a simple morphia use case, of course, there are many attributes of morphia, such as the use of mappingoption classes to configure a variety of mapping options. There are a lot of annotation in the @Entity and so on, and the extra features need to be used in the project.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.