Added support common annotation

This commit is contained in:
alex-semenyuk 2015-08-16 14:10:05 +02:00
parent 4f55bef4c3
commit a690614d49
2 changed files with 45 additions and 2 deletions

View File

@ -1,7 +1,14 @@
package org.baeldung.model;
import java.util.Calendar;
import org.baeldung.annotation.CascadeSave;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.mongodb.core.index.IndexDirection;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
@ -12,13 +19,14 @@ import com.mysema.query.annotations.QueryEntity;
@QueryEntity
@Document
@CompoundIndexes({ @CompoundIndex(name = "email_age", def = "{'email.id' : 1, 'age': 1}") })
public class User {
@Id
private String id;
@Indexed(direction = IndexDirection.ASCENDING)
private String name;
@Indexed(direction = IndexDirection.ASCENDING)
private Integer age;
@DBRef
@ -26,6 +34,19 @@ public class User {
@CascadeSave
private EmailAddress emailAddress;
@Transient
private Integer yearOfBirth;
public User() {
}
@PersistenceConstructor
public User(final String name, @Value("#root.age ?: 0") final Integer age, final EmailAddress emailAddress) {
this.name = name;
this.age = age;
this.emailAddress = emailAddress;
}
public String getId() {
return id;
}
@ -57,4 +78,8 @@ public class User {
public void setEmailAddress(EmailAddress emailAddress) {
this.emailAddress = emailAddress;
}
public Integer getYearOfBirth() {
return Calendar.getInstance().get(Calendar.YEAR) - age;
}
}

View File

@ -153,7 +153,7 @@ public class MongoTemplateQueryIntegrationTest {
public void whenSavingUserWithEmailAddress_thenUserandEmailAddressSaved() {
final User user = new User();
user.setName("Brendan");
EmailAddress emailAddress = new EmailAddress();
final EmailAddress emailAddress = new EmailAddress();
emailAddress.setValue("b@gmail.com");
user.setEmailAddress(emailAddress);
mongoTemplate.insert(user);
@ -172,4 +172,22 @@ public class MongoTemplateQueryIntegrationTest {
assertThat(indexInfos.size(), is(2));
}
@Test
public void whenSavingUserWithoutSettingAge_thenAgeIsSetByDefault() {
final User user = new User();
user.setName("Alex");
mongoTemplate.insert(user);
assertThat(mongoTemplate.findOne(Query.query(Criteria.where("name").is("Alex")), User.class).getAge(), is(0));
}
@Test
public void whenSavingUser_thenYearOfBirthIsCalculated() {
final User user = new User();
user.setName("Alex");
mongoTemplate.insert(user);
assertThat(mongoTemplate.findOne(Query.query(Criteria.where("name").is("Alex")), User.class).getYearOfBirth(), is(2015));
}
}