Integrated use of MongoDB in Spring project

Keywords: MongoDB Spring socket Database

The maven project is used here, so dependencies on jar packages are all pom.xml configuration types.

pom.xml introduces dependencies

<properties>
    <spring.version>4.3.5.RELEASE</spring.version>
</properties>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.9.8.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>2.14.2</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
</dependency>

applicationContext.xml Configuration spring Hosting

Introducing constraint mongo

xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation=" 
    http://www.springframework.org/schema/data/mongo
    http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"

spring dependency configuration

<!--Connection pool configuration-->
<mongo:mongo host="${mongo.host}" port="${mongo.port}">
    <mongo:options connections-per-host="${mongo.options.connections-per-host}"
                   threads-allowed-to-block-for-connection-multiplier="${mongo.options.threads-allowed-to-block-for-connection-multiplier}"
                   connect-timeout="${mongo.options.connect-timeout}"
                   max-wait-time="${mongo.options.max-wait-time}"
                   auto-connect-retry="${mongo.options.auto-connect-retry}"
                   socket-keep-alive="${mongo.options.socket-keep-alive}"
                   socket-timeout="${mongo.options.socket-timeout}"
                   slave-ok="${mongo.options.slave-ok}"
                   write-number="${mongo.options.write-number}"
                   write-timeout="${mongo.options.write-timeout}"
                   write-fsync="${mongo.options.write-fsync}"/>
</mongo:mongo>
<!--Connection pool factory configuration-->
<mongo:db-factory dbname="${mongo.dbname}" username="${mongo.username}" password="${mongo.password}"  mongo-ref="mongo"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
<!--Entity mapping automatically scans injected packages-->
<mongo:mapping-converter>
    <mongo:custom-converters base-package="com.xyh.mongodb_model" />
</mongo:mapping-converter>

mongo.properties

mongo.host=127.0.0.1
mongo.port=27001
mongo.dbname=test
mongo.username=testuser
mongo.password=12345
mongo.options.connections-per-host=8
mongo.options.threads-allowed-to-block-for-connection-multiplier=4
mongo.options.connect-timeout=1000
mongo.options.max-wait-time=1500
mongo.options.auto-connect-retry=true
mongo.options.socket-keep-alive=true
mongo.options.socket-timeout=1500
mongo.options.slave-ok=false
mongo.options.write-number=1
mongo.options.write-timeout=0
mongo.options.write-fsync=true
  • mongo.host:ip address of the host where the mongoDB database is located
  • mongo.port: mongoDB database uses communication ports
  • mongo.dbname: The database name used for the connection
  • mongo.username: The database operation user name
  • mongo.password: This database operates on user passwords

Entity class

@Document
public class LoginHistory {
    @Id
    private String id;

    @Indexed
    private String uid;

    private String ip;

    private String imei;

    @Indexed(direction = IndexDirection.DESCENDING)
    private String timestamp;

    private String longitude;

    private String latitude;

    private String address;

    @PersistenceConstructor
    public LoginHistory( String id, String uid, String ip, String imei, String timestamp, String longitude, String latitude, String address) {
        this.id = id;
        this.uid = uid;
        this.ip = ip;
        this.imei = imei;
        this.timestamp = timestamp;
        this.longitude = longitude;
        this.latitude = latitude;
        this.address = address;
    }

    public String getId() {
        return id;
    }

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

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getImei() {
        return imei;
    }

    public void setImei(String imei) {
        this.imei = imei;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String getLongitude() {
        return longitude;
    }

    public void setLongitude(String longitude) {
        this.longitude = longitude;
    }

    public String getLatitude() {
        return latitude;
    }

    public void setLatitude(String latitude) {
        this.latitude = latitude;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

@ Id - The unique identifier of a document, which is ObjectId in mongodb, is unique. It consists of a timestamp + machine identifier + process ID + self-incremental counter (to ensure that the Id generated in the same second does not conflict).

@ Document - Documents that declare a java class as mongodb can be specified by the collection parameter. @ Document(collection= "mongodb") mongodb correspondence table

@ DBRef - Declares associations similar to relational databases. ps: Cascade saving is not supported. When you modify the values in the DERef object in this example, saving this example alone does not save the object referenced by DERef. It needs to be saved separately, such as Person and Acount of the following examples.

@ Indexed - Declares that the field needs an index, which can greatly improve query efficiency.

@ Compound Index - The declaration of composite index and the construction of composite index can effectively improve the query efficiency of multi-field.

@ GeoSpatial Indexed - Declares that the field is an index of geographic information.

@ Transient - A field ignored by the mapping, which is not saved to mongodb.

@ Persistence Constructor - Declares a constructor that instantiates data taken from a database into objects. The constructor passes in the value of the data taken from the DBObject

Adding, deleting, modifying and checking operation classes

Injecting mongoTemplate configured in xml into dao
MongoOperations are the parent of MongoTemplate

@Autowired
private MongoOperations mongoOperations;
//save is updated if it exists, and insert if it does not exist
public void save(LoginHistory loginHistory){
    mongoOperations.save(loginHistory);
}

//Insert exists without processing, and insert if it does not exist
public void insert(LoginHistory loginHistory){
    mongoOperations.insert(loginHistory);
}

//Delete documents according to uid
public void remove(String uid){
    Query query = new Query();
    query.addCriteria(Criteria.where("uid").is(uid));
    mongoOperations.remove(query,LoginHistory.class);
}

//Update documents according to id
public int update(LoginHistory loginHistory){
    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(loginHistory.getId()));
    Update update = new Update();
    update.set("uid",loginHistory.getUid());
    update.set("ip",loginHistory.getIp());
    update.set("imei",loginHistory.getImei());
    update.set("timestamp",loginHistory.getTimestamp());
    update.set("longitude",loginHistory.getLongitude());
    update.set("latitude",loginHistory.getLatitude());
    update.set("address",loginHistory.getAddress());
    return mongoOperations.updateFirst(query,update,LoginHistory.class).getN();
}

//Single condition query, find query all
public List<LoginHistory> findByUid(String uid){
    Query query = new Query();
    query.addCriteria(Criteria.where("uid").is(uid));
    return mongoOperations.find(query,LoginHistory.class);
}

//Multi-condition query, find query all
public List<LoginHistory> findByUidAndTimestamp(String uid,String startTimestamp,String endTimestamp){
    Query query = new Query();
    query.addCriteria(Criteria.where("uid").is(uid).and("timestamp").gte(startTimestamp).lte(endTimestamp));
    return mongoOperations.find(query,LoginHistory.class);
}



//Paging queries based on uid
public List<LoginHistory> page(int page,String uid){
    Query query = new Query();
    query.addCriteria(Criteria.where("uid").is(uid));
    query.with(new Sort(new Sort.Order(Sort.Direction.DESC,"timestamp")));
    query.limit(20);
    query.skip((page-1)*20);
    return mongoOperations.find(query,LoginHistory.class);
}

Posted by cubik on Thu, 06 Jun 2019 11:26:33 -0700