我使用的是最新的spring-data-mongodb(1.1.0.M2)和最新的Mongo Driver(2.9.0-RC1).我有一种情况,我有多个客户端连接到我的应用程序,我想在同一个Mongo服务器中给每个客户端自己的"架构/数据库".如果我直接使用驱动程序,这不是一项非常困难的任务:
Mongo mongo = new Mongo( new DBAddress( "localhost", 127017 ) );
DB client1DB = mongo.getDB( "client1" );
DBCollection client1TTestCollection = client1DB.getCollection( "test" );
long client1TestCollectionCount = client1TTestCollection.count();
DB client2DB = mongo.getDB( "client2" );
DBCollection client2TTestCollection = client2DB.getCollection( "test" );
long client2TestCollectionCount = client2TTestCollection.count();
Run Code Online (Sandbox Code Playgroud)
看,很容易.但是spring-data-mongodb不允许使用多个数据库的简单方法.设置连接的首选方法Mongo是扩展AbstractMongoConfiguration类:
您将看到重写以下方法:
getDatabaseName()
Run Code Online (Sandbox Code Playgroud)
因此它强制您使用一个数据库名称.然后构建的存储库接口使用传递给SimpleMongoRepository类的MongoTemplate中的数据库名称.
我到底在哪里粘贴多个数据库名称?我必须创建多个数据库名称,多个MongoTempates(每个数据库名称一个)和多个其他配置类.而且仍然没有让我的存储库接口使用正确的模板.如果有人尝试过这样的事情,请告诉我.如果我搞清楚,我会在这里发布答案.
谢谢.
在我的项目中,我在进行单元测试时遇到了麻烦.一个问题是,只进行集成测试要快得多,并且还要测试组件实际上是否一起工作.单元测试新颖的"算法"左右似乎要容易得多.单元测试服务类它只是感觉错误和无用.
我正在使用mockito来模拟spring数据存储库(因此也就是DB访问).问题是如果我告诉模拟的存储库在方法调用getById上返回实体A,它显然会返回它,服务也将返回它.是的,该服务会做一些额外的东西,但是非常小的东西,比如加载延迟集合(来自hibernate).显然我在单元测试中没有任何惰性集合(代理).
例:
@Test
public void testGetById() {
System.out.println("getById");
TestCompound expResult = new TestCompound(id, "Test Compound", "9999-99-9", null, null, null);
TestCompoundRepository mockedRepository = mock(TestCompoundRepository.class);
when(mockedRepository.findOne(id)).thenReturn(expResult);
ReflectionTestUtils.setField(testCompoundService, "testCompoundRepository",
mockedRepository, TestCompoundRepository.class);
TestCompound result = testCompoundService.getById(id);
assertEquals(expResult, result);
}
Run Code Online (Sandbox Code Playgroud)
万岁,其余的都成功了.多么惊喜!不是真的没有.
有人可以向我解释我做错了什么吗?或者这样一个测试的重点是什么?我的意思是我告诉返回expResult然后它返回.哇.多么惊喜!感觉就像我在测试mockito是否有效,而不是我的服务.
编辑:
我看到的唯一好处是,如果有些是愚蠢的错误,就像在那里留下一个不需要的行,将返回值设置为null或类似的愚蠢.这种情况将由单元测试捕获."奖励 - 努力"比例看起来还不错吗?
我正在尝试做一些我认为应该非常简单的事情.我有一个Question对象,设置有spring-boot,spring-data-rest和spring-hateoas.所有的基础工作都很好.我想添加一个自定义控制器,它返回一个List<Question>与我Repository的/questions网址完全相同的格式,以便两者之间的响应兼容.
这是我的控制器:
@Controller
public class QuestionListController {
@Autowired private QuestionRepository questionRepository;
@Autowired private PagedResourcesAssembler<Question> pagedResourcesAssembler;
@Autowired private QuestionResourceAssembler questionResourceAssembler;
@RequestMapping(
value = "/api/questions/filter", method = RequestMethod.GET,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody PagedResources<QuestionResource> filter(
@RequestParam(value = "filter", required = false) String filter,
Pageable p) {
// Using queryDSL here to get a paged list of Questions
Page<Question> page =
questionRepository.findAll(
QuestionPredicate.findWithFilter(filter), p);
// Option 1 - default resource assembler
return …Run Code Online (Sandbox Code Playgroud) spring spring-mvc spring-data spring-data-rest spring-hateoas
假设我有实体(为了简洁省略了getter/setter和各种细节):
@Entity
class Customer{
...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
Collection<Coupon> coupons;
}
@Entity
class Coupon{
...
@Temporal(value = TemporalType.TIMESTAMP)
private Date usedOn;
@ManyToOne(fetch = FetchType.LAZY)
@NotNull
Customer customer;
}
Run Code Online (Sandbox Code Playgroud)
我希望检索具有null usedOn的给定客户的所有优惠券.我没有成功定义CouponRepository中的方法,如文档中所述
@Repository
public interface CouponRepository extends CrudRepository<Coupon, Long> {
Collection<Coupon> findByCustomerAndUsedOnIsNull(Customer);
}
Run Code Online (Sandbox Code Playgroud)
但这会导致编译错误Syntax error, insert "... VariableDeclaratorId" to complete FormalParameterList.
我在CrudRepository整个申请过程中都使用了spring .现在我想创建一个@Entity没有的@Id.这有可能吗?
//probably ID is always required?
public interface Repository<T, ID extends Serializable>
Run Code Online (Sandbox Code Playgroud) 是否可以使用Spring Data Rest为同一JPA实体发布两个不同的存储库?我为这两个存储库提供了不同的路径和rel-name,但只有两个中的一个可用作REST端点.我有两个存储库的原因是,其中一个是摘录,仅显示实体的基本字段.
在我的Spring Boot项目中,我实现了以下服务方法:
@Transactional
public boolean validateBoard(Board board) {
boolean result = false;
if (inProgress(board)) {
if (!canPlayWithCurrentBoard(board)) {
update(board, new Date(), Board.AFK);
throw new InvalidStateException(ErrorMessage.BOARD_TIMEOUT_REACHED);
}
if (!canSelectCards(board)) {
update(board, new Date(), Board.COMPLETED);
throw new InvalidStateException(ErrorMessage.ALL_BOARD_CARDS_ALREADY_SELECTED);
}
result = true;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
在这个方法里面,我使用另一种叫做的服务方法update:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Board update(Board board, Date finishedDate, Integer status) {
board.setStatus(status);
board.setFinishedDate(finishedDate);
return boardRepository.save(board);
}
Run Code Online (Sandbox Code Playgroud)
我需要update独立于validateBoard方法中启动的所有者事务,在方法中提交对数据库的更改.现在任何变化都会在任何异常的情况下回滚.
即使@Transactional(propagation = Propagation.REQUIRES_NEW)它不起作用.
如何使用Spring正确执行此操作并允许嵌套事务?
spring spring-transactions spring-data spring-data-jpa spring-boot
我想知道如果它在数据库中找到已经存在的条目,那么该{save}方法CrudRepository是否进行更新:
@Repository
public interface ProjectDAO extends CrudRepository<Project, Integer> {}
@Service
public class ProjectServiceImpl {
@Autowired private ProjectDAO pDAO;
public void save(Project p) { pDAO.save(p); } }
Run Code Online (Sandbox Code Playgroud)
因此,如果我在已注册的条目上调用该方法,它会在找到更改的属性时更新它吗?
谢谢.
我有两个域对象,
@Document
public class PracticeQuestion {
private int userId;
private List<Question> questions;
// Getters and setters
}
@Document
public class Question {
private int questionID;
private String type;
// Getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我的JSON文档是这样的,
{
"_id" : ObjectId("506d9c0ce4b005cb478c2e97"),
"userId" : 1,
"questions" : [
{
"questionID" : 1,
"type" : "optional"
},
{
"questionID" : 3,
"type" : "mandatory"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我必须更新基于userId和questionId的"类型",所以我在自定义Repository接口中编写了一个findBy查询方法,
public interface CustomRepository extends MongoRepository<PracticeQuestion, String> {
List<PracticeQuestion> findByUserIdAndQuestionsQuestionID(int userId,int questionID);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是当我执行此方法时userId为1而questionID为3,它返回整个问题列表而不管questionID.查询方法名称是有效的,还是应该如何为嵌套对象编写查询.
谢谢你的任何建议.
生成我的实体ID,当我使用DAO而不是Spring数据JPA时它工作正常.
@Id
@Column(name = TABLE_COLUM_NAME_ID)
@GeneratedValue
private int id;
Run Code Online (Sandbox Code Playgroud)
现在我已经开始使用Spring数据JPA,在我打电话之后repository.save(myboject),或者repository.saveAndFlush(myobject),我打电话myobject.getId().但是id从未填充过.
我搜索了我的数据库,对象在数据库中,ID正确.有谁知道为什么我打电话后没有设置id save()?我用的时候没问题entitymanager.save().
spring-data ×10
spring ×7
java ×3
spring-mvc ×3
jpa ×2
mongodb ×2
database ×1
findby ×1
hibernate ×1
spring-boot ×1
unit-testing ×1