mongo 学习日志(一)插入数据

  1. 插入数据
    		String firstName = RandomStringUtils.randomAlphabetic(7);
    		String lastName = RandomStringUtils.randomAlphabetic(7);
    		Customer customer = new Customer(firstName, lastName);
    		mongoTemplate.save(customer);

    Customer.java
    package com.demo.entity;
    
    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;
    
    @Document(collection = "Customer")
    public class Customer {
    	@Id
    	private String id;
    	
    	private String firstName;
    	private String lastName;
    
    	public Customer() {
    	}
    
    	public Customer(String firstName, String lastName) {
    		this.firstName = firstName;
    		this.lastName = lastName;
    	}
    
    	@Override
    	public String toString() {
    		return String.format("Customer[id=%s, firstName='%s', lastName='%s']",
    				id, firstName, lastName);
    	}
    }
    

    插入结果

    NOTE: 插入结果中多了一列_class.

    解决

    <mongo:mongo host="127.0.0.1" port="27017"/>
    <mongo:db-factory dbname="database" mongo-ref="mongo"/>
    
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
        <!-- <constructor-arg name="mongoConverter" ref="mappingConverter" /> -->
    </bean>
    查了查资料,发现如果使用默认配置,数据库里面将会添加 “_class”.更改为如下配置后,“_class”被移除。
    <!-- Default bean name is 'mongo' -->
    <mongo:mongo host="localhost" port="27017"/>
    <mongo:db-factory dbname="database"/>
    
    <bean id="mappingContext"
     class="org.springframework.data.mongodb.core.mapping.MongoMappingContext"/>
    
    <bean id="defaultMongoTypeMapper"
     class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
        <constructor-arg name="typeKey">
            <null/>
        </constructor-arg>
    </bean>
    
    <bean id="mappingMongoConverter"
     class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
        <constructor-arg name="mappingContext" ref="mappingContext"/>
        <property name="typeMapper" ref="defaultMongoTypeMapper"/>
    </bean>
    
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
        <constructor-arg name="mongoConverter" ref="mappingMongoConverter"/>
    </bean>
    参考
    1. http://www.mkyong.com/mongodb/spring-data-mongodb-remove-_class-column/
    2. http://stackoverflow.com/questions/6810488/spring-data-mongodb-mappingmongoconverter-remove-class

你可能感兴趣的:(mongo 学习日志(一)插入数据)