MongoMappingConverter

来源:互联网 发布:手机扬声器检测软件 编辑:程序博客网 时间:2024/06/17 05:56

12.2. Data mapping and type conversion

This section explain how types are mapped to a MongoDB representation and vice versa. Spring Data MongoDB supports all types that can be represented as BSON, MongoDB’s internal document format. In addition to these types, Spring Data MongoDB provides a set of built-in converters to map additional types. You can provide your own converters to adjust type conversion, see Overriding Mapping with explicit Converters for further details.

Table 7. TypeTypeType conversionSample

String

native

{"firstname" : "Dave"}

doubleDoublefloatFloat

native

{"weight" : 42.5}

intIntegershortShort

native
32-bit integer

{"height" : 42}

longLong

native
64-bit integer

{"height" : 42}

DateTimestamp

native

{"date" : ISODate("2019-11-12T23:00:00.809Z")}

byte[]

native

{"bin" : { "$binary" : "AQIDBA==", "$type" : "00" }}

java.util.UUID (Legacy UUID)

native

{"uuid" : { "$binary" : "MEaf1CFQ6lSphaa3b9AtlA==", "$type" : "03" }}

Date

native

{"date" : ISODate("2019-11-12T23:00:00.809Z")}

ObjectId

native

{"_id" : ObjectId("5707a2690364aba3136ab870")}

Array, ListBasicDBList

native

{"cookies" : [ … ]}

booleanBoolean

native

{"active" : true}

null

native

{"value" : null}

DBObject

native

{"value" : { … }}

AtomicInteger
calling get() before the actual conversion

converter
32-bit integer

{"value" : "741" }

AtomicLong
calling get() before the actual conversion

converter
64-bit integer

{"value" : "741" }

BigInteger

converter
String

{"value" : "741" }

BigDecimal

converter
String

{"value" : "741.99" }

URL

converter

{"website" : "http://projects.spring.io/spring-data-mongodb/" }

Locale

converter

{"locale : "en_US" }

charCharacter

converter

{"char" : "a" }

NamedMongoScript

converter
Code

{"_id" : "script name", value: (some javascript code)}

java.util.Currency

converter

{"currencyCode" : "EUR"}

LocalDate
(Joda, Java 8, JSR310-BackPort)

converter

{"date" : ISODate("2019-11-12T00:00:00.000Z")}

LocalDateTimeLocalTimeInstant
(Joda, Java 8, JSR310-BackPort)

converter

{"date" : ISODate("2019-11-12T23:00:00.809Z")}

DateTime (Joda)

converter

{"date" : ISODate("2019-11-12T23:00:00.809Z")}

DateMidnight (Joda)

converter

{"date" : ISODate("2019-11-12T00:00:00.000Z")}

ZoneId (Java 8, JSR310-BackPort)

converter

{"zoneId" : "ECT - Europe/Paris"}

Box

converter

{"box" : { "first" : { "x" : 1.0 , "y" : 2.0} , "second" : { "x" : 3.0 , "y" : 4.0}}

Polygon

converter

{"polygon" : { "points" : [ { "x" : 1.0 , "y" : 2.0} , { "x" : 3.0 , "y" : 4.0} , { "x" : 4.0 , "y" : 5.0}]}}

Circle

converter

{"circle" : { "center" : { "x" : 1.0 , "y" : 2.0} , "radius" : 3.0 , "metric" : "NEUTRAL"}}

Point

converter

{"point" : { "x" : 1.0 , "y" : 2.0}}

GeoJsonPoint

converter

{"point" : { "type" : "Point" , "coordinates" : [3.0 , 4.0] }}

GeoJsonMultiPoint

converter

{"geoJsonLineString" : {"type":"MultiPoint", "coordinates": [ [ 0 , 0 ], [ 0 , 1 ], [ 1 , 1 ] ] }}

Sphere

converter

{"sphere" : { "center" : { "x" : 1.0 , "y" : 2.0} , "radius" : 3.0 , "metric" : "NEUTRAL"}}

GeoJsonPolygon

converter

{"polygon" : { "type" : "Polygon", "coordinates" : [[ [ 0 , 0 ], [ 3 , 6 ], [ 6 , 1 ], [ 0 , 0 ] ]] }}

GeoJsonMultiPolygon

converter

{"geoJsonMultiPolygon" : { "type" : "MultiPolygon", "coordinates" : [ [ [ [ -73.958 , 40.8003 ] , [ -73.9498 , 40.7968 ] ] ], [ [ [ -73.973 , 40.7648 ] , [ -73.9588 , 40.8003 ] ] ] ] }}

GeoJsonLineString

converter

{ "geoJsonLineString" : { "type" : "LineString", "coordinates" : [ [ 40 , 5 ], [ 41 , 6 ] ] }}

GeoJsonMultiLineString

converter

{"geoJsonLineString" : { "type" : "MultiLineString", coordinates: [ [ [ -73.97162 , 40.78205 ], [ -73.96374 , 40.77715 ] ], [ [ -73.97880 , 40.77247 ], [ -73.97036 , 40.76811 ] ] ] }}

12.3. Mapping Configuration

Unless explicitly configured, an instance of MongoMappingConverter is created by default when creating a MongoTemplate. You can create your own instance of the MappingMongoConverter so as to tell it where to scan the classpath at startup your domain classes in order to extract metadata and construct indexes. Also, by creating your own instance you can register Spring converters to use for mapping specific classes to and from the database.

You can configure the MongoMappingConverter as well as com.mongodb.Mongo and MongoTemplate either using Java or XML based metadata. Here is an example using Spring’s Java based configuration

Example 84. @Configuration class to configure MongoDB mapping support
@Configurationpublic class GeoSpatialAppConfig extends AbstractMongoConfiguration {  @Bean  public Mongo mongo() throws Exception {    return new Mongo("localhost");  }  @Override  public String getDatabaseName() {    return "database";  }  @Override  public String getMappingBasePackage() {    return "com.bigbank.domain";  }  // the following are optional  @Bean  @Override  public CustomConversions customConversions() throws Exception {    List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();    converterList.add(new org.springframework.data.mongodb.test.PersonReadConverter());    converterList.add(new org.springframework.data.mongodb.test.PersonWriteConverter());    return new CustomConversions(converterList);  }  @Bean  public LoggingEventListener<MongoMappingEvent> mappingEventsListener() {    return new LoggingEventListener<MongoMappingEvent>();  }}

AbstractMongoConfiguration requires you to implement methods that define a com.mongodb.Mongo as well as provide a database name. AbstractMongoConfiguration also has a method you can override namedgetMappingBasePackage(…) which tells the converter where to scan for classes annotated with the @Documentannotation.

You can add additional converters to the converter by overriding the method afterMappingMongoConverterCreation. Also shown in the above example is a LoggingEventListener which logs MongoMappingEvent s that are posted onto Spring’s ApplicationContextEvent infrastructure.

AbstractMongoConfiguration will create a MongoTemplate instance and registered with the container under the name mongoTemplate.

You can also override the method UserCredentials getUserCredentials() to provide the username and password information to connect to the database.

Spring’s MongoDB namespace enables you to easily enable mapping functionality in XML

Example 85. XML schema to configure MongoDB mapping support
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xmlns:context="http://www.springframework.org/schema/context"  xmlns:mongo="http://www.springframework.org/schema/data/mongo"  xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd    http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  <!-- Default bean name is 'mongo' -->  <mongo:mongo host="localhost" port="27017"/>  <mongo:db-factory dbname="database" mongo-ref="mongo"/>  <!-- by default look for a Mongo object named 'mongo' - default name used for the converter is 'mappingConverter' -->  <mongo:mapping-converter base-package="com.bigbank.domain">    <mongo:custom-converters>      <mongo:converter ref="readConverter"/>      <mongo:converter>        <bean class="org.springframework.data.mongodb.test.PersonWriteConverter"/>      </mongo:converter>    </mongo:custom-converters>  </mongo:mapping-converter>  <bean id="readConverter" class="org.springframework.data.mongodb.test.PersonReadConverter"/>  <!-- set the mapping converter to be used by the MongoTemplate -->  <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>    <constructor-arg name="mongoConverter" ref="mappingConverter"/>  </bean>  <bean class="org.springframework.data.mongodb.core.mapping.event.LoggingEventListener"/></beans>

The base-package property tells it where to scan for classes annotated with the @org.springframework.data.mongodb.core.mapping.Document annotation.

0 0
原创粉丝点击