我在执行 MongoOperations 类的 findOne 方法时遇到了一些问题,现在这个方法返回 null。我在 mongoDB 中的数据结构如下所示:
> db.news.find({_id:1})
{ "_id" : 1, "title" : "first title", "text" : "first text" }
> db.news.find({_id:{$type:1}})
{ "_id" : 1, "title" : "first title", "text" : "first text" }
Run Code Online (Sandbox Code Playgroud)
正如您在上面看到的 _id 字段具有 Double 类型。我的 Java 类看起来像这样:
@Repository
public class NewsService {
@Autowired
private MongoOperations mongoOperations;
public static final String COLLECTION_NAME = "news";
//this method executes ok
public List<NewsEntity> getAllNews() {
return mongoOperations.findAll(NewsEntity.class, COLLECTION_NAME);
}
//but this method return null
public NewsEntity …Run Code Online (Sandbox Code Playgroud) 我正在使用 Spring Data JPA 框架中的 JpaRepository。我在下面有一段代码:
@Repository
public interface PresetFolderRepository extends JpaRepository<PresetFolder, Integer>{
@Modifying
@Transactional
@Query("update PresetFolder pf set pf.parentId = :parentId where pf.id = :id")
int updateParentId(@Param("id") int id, @Param("parentId") int parentId);
}
Run Code Online (Sandbox Code Playgroud)
当我调用这个方法时:
@Autowired PresetFolderRepository repo;
repo.updateParentId(1,2);
public void test(){
Run Code Online (Sandbox Code Playgroud)
我必须用 try-catch 包围它吗?我如何知道自定义方法“updateParentId”中是否有 try-catch 实现?
谢谢!
编辑:我担心的是,如果我的数据库出现故障,此方法是否会捕获异常。
我正在使用Springboot MySQL示例(类似示例)。在其中一种方法中,我想记录JSON数据,但我得到了,
com.example.employee.model.Employee@1595ddd2
@RequestMapping(value="/employees12/{id}", method=RequestMethod.GET)
public Employee getPerson(@PathVariable Long id){
Employee employee = employeeRepository.findOne(id);
//String str=employee.toString();
//System.out.println("string is " + str);
System.out.println(employee); //print json in logs console
return employee;
}
Run Code Online (Sandbox Code Playgroud)
该return employees;是给JSON数据。我尝试过toString(),即使这样也不起作用。任何帮助表示赞赏。
我正在使用Spring Boot应用程序尝试与手动数据源连接,当运行项目时出现异常:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountController': Unsatisfied dependency expressed through field 'accountService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountServiceImpl': Unsatisfied dependency expressed through field 'accountDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.springstudy.demo.model.Account
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.8.RELEASE.jar:5.0.8.RELEASE] …Run Code Online (Sandbox Code Playgroud) 首先,目标.什么是单元测试?单元测试是测试最小功能的测试,与测试更多的集成测试相反,例如:
src/main/resources测试不是单元测试那么,如何为Spring Data JPA存储库编写单元测试?(或者那么受欢迎和喜爱的框架不支持纯单元测试这样的事情吗?)
我的项目:Spring Cloud(云计算服务,安全OAuth2服务,尤里卡,zuul,身份验证,授权等)
让我们尝试测试最简单的存储库:
public interface StudentRepository extends CrudRepository<Student, Integer> {
Optional<Student> findByStudentCode(Integer studentCode);
Optional<Student> findTopByOrderByStudentCodeDesc();
@Query(value = "SELECT COUNT(*) = 0 FROM t_student WHERE regexp_replace(LOWER(student_name), '\\s', '', 'g') = regexp_replace(LOWER(:suspect), '\\s', '', 'g')", nativeQuery = true)
boolean isStudentNameSpeciallyUnique(@Param("suspect") String studentName);
}
Run Code Online (Sandbox Code Playgroud)
学生实体将具有:id,代码(自然ID),姓名,年龄.没什么特别的.这是测试.我们需要一个SUT(我们的存储库)和实体管理器来预填充SUT.所以:
@RunWith(SpringRunner.class)
@DataJpaTest // <-- loads full-blown production app context and fails!
public class StudentRepositoryTest {
@Autowired
TestEntityManager manager;
@Autowired
StudentRepository repository;
@Test
public void findByStudentCode_whenNoSuch_shouldReturnEmptyOptional() …Run Code Online (Sandbox Code Playgroud) unit-testing spring-test spring-data-jpa spring-boot spring-cloud
我的问题如下.伪代码如下:
public Object rollBackTestMainMethod(List<Object> list) {
List<Object> responseList = new ArrayList<>();
for(Object item:list){
try{
Boolean isOperationSuccess = rollBackTestSubMethod(item);
if (isOperationSuccess==null || !isOperationSuccess){
item.addError("Operation failed");
item.addSuccess(false);
} else {
item.addError(null);
item.addSuccess(true);
}
} catch(Exception exception) {
item.addError(exception.getMessage());
item.addSuccess(false);
}
responseList.add(item);
}
return responseList;
}
@Transactional(rollbackFor = {Exception.class, SQLException.class})
private Boolean rollBackTestSubMethod(Object listItem){
Long value1=save(listItem.getValue1());
if(value1==null){
throw new Exception("Error during save 1");
}
Long value2=save(listItem.getValue2());
if(value2==null){
throw new Exception("Error during save 2");
}
Long value3=save(listItem.getValue3());
if(value3==null){
throw new Exception("Error during …Run Code Online (Sandbox Code Playgroud) Spring Data JPA不是JPA实现,它是对数据库数据访问的抽象。在与JPA的实现进行比较的领域(例如Hibernate),我无法理解该表达式。使用Spring Data JPA时,要使用CRUD操作,必须从CrudRepository接口进行扩展。但是如果没有Hibernate,Spring Data JPA无法独立工作,因为它无法将Java对象转换为Entity。但!Hibernate也可以执行CRUD操作。所以问题是: 1.如果我们仍然需要使用HIBERNATE,为什么开发人员会使用Spring Data JPA(精确地是CRUD操作)?2. CrudRepository接口只是一个接口,它是从“ Repository”接口扩展而来的。我们在CRUD类中扩展它以实现CRUD操作。我不明白它是如何工作的。我们的类如何简单地通过扩展接口来执行CRUD操作。没有实现的方法。 我现在如何回答这些问题:
我们可以使用spring data JPA执行所有数据库操作吗?我们可以使用spring数据JPA执行所有复杂的事情,例如缓存,存储过程等,并使用spring数据JPA代替休眠吗?
我遇到的所有示例都只使用了带有Spring Boot的spring数据JPA。
我有一个Spring Boot应用程序,它具有这样的存储库。
public interface EmployeeRepository extends CrudRepository<Employee, Long> {
List<Employee> findTop3ByOrderBySalaryDesc();
}
Run Code Online (Sandbox Code Playgroud)
findTop3ByOrderBySalaryDesc在上面的功能中,找到薪水最高的前3名员工。在此示例中,是否可以动态指定雇员人数?例如,是否可以为此函数分配一个整数参数来确定员工人数?
我确实有一些问题,无法理解当将Stream来自Spring数据jpa的查询结果接收到的手动包装到a中时,幕后是怎么回事Flux。
考虑以下:
实体:
@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
public class TestEntity {
@Id
private Integer a;
private Integer b;
}
Run Code Online (Sandbox Code Playgroud)
仓库:
public interface TestEntityRepository extends JpaRepository<TestEntity, Integer> {
Stream<TestEntity> findByBBetween(int b1, int b2);
}
Run Code Online (Sandbox Code Playgroud)
简单的测试代码:
@Test
@SneakyThrows
@Transactional
public void dbStreamToFluxTest() {
testEntityRepository.save(new TestEntity(2, 6));
testEntityRepository.save(new TestEntity(3, 8));
testEntityRepository.save(new TestEntity(4, 10));
testEntityFlux(testEntityStream()).subscribe(System.out::println);
testEntityFlux().subscribe(System.out::println);
Thread.sleep(200);
}
private Flux<TestEntity> testEntityFlux() {
return fromStream(this::testEntityStream);
}
private Flux<TestEntity> testEntityFlux(Stream<TestEntity> testEntityStream) {
return fromStream(() -> testEntityStream);
}
private Stream<TestEntity> testEntityStream() {
return …Run Code Online (Sandbox Code Playgroud) java transactions spring-data-jpa java-stream project-reactor
spring-data-jpa ×10
java ×8
spring-boot ×5
hibernate ×4
spring ×3
java-stream ×1
jpa ×1
mongodb ×1
spring-cloud ×1
spring-mvc ×1
spring-test ×1
transactions ×1
unit-testing ×1