标签: spring-data-jpa

在 Spring Data (MongoDB) 中实现 findOne

我在执行 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)

java spring-mvc mongodb spring-data-jpa

1
推荐指数
1
解决办法
2万
查看次数

我是否必须尝试捕获 JpaRepository

我正在使用 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 实现?

谢谢!

编辑:我担心的是,如果我的数据库出现故障,此方法是否会捕获异常。

spring spring-data-jpa

1
推荐指数
1
解决办法
4038
查看次数

在SpringBoot JPA方法中将Java对象转换为字符串

我正在使用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(),即使这样也不起作用。任何帮助表示赞赏。

java spring-data-jpa spring-boot

1
推荐指数
1
解决办法
1619
查看次数

Spring Boot(2.0.4.RELEASE)-IllegalArgumentException:不是托管类型

我正在使用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)

java hibernate spring-data-jpa spring-boot

1
推荐指数
2
解决办法
4385
查看次数

真的,不可能对Spring Data JPA @Query进行单元测试吗?

首先,目标.什么是单元测试?单元测试是测试最小功能的测试,与测试更多的集成测试相反,例如:

  • 以任何方式或任何形式生成ApplicationContext的测试不是单元测试;
  • 触摸甚至意识到应用程序(标有@SpringBootApplication)类的测试不是单元测试;
  • 加载某些东西的src/main/resources测试不是单元测试
  • 从Spring Cloud Config服务器加载外部配置的测试绝对不是单元测试;
  • 存储库的单元测试不得启动(甚至不知道)web,mvc或安全问题.

那么,如何为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

1
推荐指数
1
解决办法
1260
查看次数

使用try catch,Spring @Transactional anotation无法在for循环中工作

我的问题如下.伪代码如下:

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)

java spring hibernate spring-data-jpa spring-boot

1
推荐指数
1
解决办法
645
查看次数

Spring Data JPA和Hibernate

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操作。没有实现的方法。 我现在如何回答这些问题:

  1. 是为了简化代码。由于通过Hibernate使用CRUD操作需要更多代码。
  2. 目前,只有一种想法可以想到:CrudRepository接口以某种(“神奇的”)方式使用标准的Hibernate工具来使用CRUD操作。

java hibernate spring-data-jpa

1
推荐指数
1
解决办法
91
查看次数

使用Spring数据JPA代替休眠

我们可以使用spring data JPA执行所有数据库操作吗?我们可以使用spring数据JPA执行所有复杂的事情,例如缓存,存储过程等,并使用spring数据JPA代替休眠吗?

我遇到的所有示例都只使用了带有Spring Boot的spring数据JPA。

java hibernate jpa spring-data-jpa spring-boot

1
推荐指数
1
解决办法
249
查看次数

在Spring JPA存储库中的findByTopN中动态设置N

我有一个Spring Boot应用程序,它具有这样的存储库。

public interface EmployeeRepository extends CrudRepository<Employee, Long> {
  List<Employee> findTop3ByOrderBySalaryDesc();
}
Run Code Online (Sandbox Code Playgroud)

findTop3ByOrderBySalaryDesc在上面的功能中,找到薪水最高的前3名员工。在此示例中,是否可以动态指定雇员人数?例如,是否可以为此函数分配一个整数参数来确定员工人数?

java spring spring-data-jpa

1
推荐指数
1
解决办法
28
查看次数

将Stream包装到Flux中时的事务处理

我确实有一些问题,无法理解当将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

1
推荐指数
1
解决办法
122
查看次数