标签: spring-data

在Spring中配置特定的内存数据库以进行测试

如何配置我的Spring Boot应用程序,以便在运行单元测试时,它将使用内存数据库,如H2/HSQL,但是当我运行Spring Boot应用程序时,它将使用生产数据库[Postgre/MySQL]?

spring spring-test spring-data spring-test-dbunit spring-boot

38
推荐指数
6
解决办法
4万
查看次数

org.hibernate.AnnotationException:没有为实体指定标识符 - 即使它是

我有以下配置:

<bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="jpaDataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan">
        <list>
            <value>com.example.domain</value>
            <value>com.example.repositories</value>
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

我在com.example.domain中有我的Geoname类:

@Entity
@Table(name="geonames")
public class Geoname implements Serializable {

    @Id
    @Column(name="geonameid")
    private Long geonameid = null;
}
Run Code Online (Sandbox Code Playgroud)

但是,在运行时,我得到以下异常:

org.hibernate.AnnotationException:通过引起指定实体没有标识符:com.example.domain.Geoname在org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:277)在org.hibernate.cfg.InheritanceState.getElementsToProcess( InheritanceState.java:224)在org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:664)在org.hibernate.cfg.Configuration $ MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3449)在org.hibernate.cfg.Configuration $ MetadataSourceQueue.processMetadata(Configuration.java:3403)在org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1330)在org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1730)

有什么想法吗?

旁注:我在这个项目中将mongodb和hibernate/mysql结合起来.

spring hibernate spring-data spring-data-jpa

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

隔离控制器测试无法实例化Pageable

我有一个Spring MVC控制器,它使用Spring-Data的分页支持:

@Controller
public class ModelController {

    private static final int DEFAULT_PAGE_SIZE = 50;

    @RequestMapping(value = "/models", method = RequestMethod.GET)
    public Page<Model> showModels(@PageableDefault(size = DEFAULT_PAGE_SIZE) Pageable pageable, @RequestParam(
            required = false) String modelKey) {

//..
        return models;
    }

}
Run Code Online (Sandbox Code Playgroud)

我想使用漂亮的Spring MVC测试支持测试RequestMapping.为了使这些测试保持快速并与所有其他内容隔离开来,我不想创建完整的ApplicationContext:

public class ModelControllerWebTest {
    private MockMvc mockMvc;

    @Before
    public void setup() {
        ModelController controller = new ModelController();
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void reactsOnGetRequest() throws Exception {
        mockMvc.perform(get("/models")).andExpect(status().isOk());
    }

}
Run Code Online (Sandbox Code Playgroud)

这种方法适用于其他控制器,它们不期望使用Pageable,但是有了这个,我得到了一个很好的长Spring堆栈跟踪.它抱怨无法实例化Pageable:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is …
Run Code Online (Sandbox Code Playgroud)

testing spring-mvc spring-data spring-mvc-test

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

在JSON中禁用超文本应用程序语言(HAL)?

在版本2.0.2.RELEASE中使用带有JPA的Spring Data REST.

如何在JSON中禁用超文本应用程序语言(HAL)?http://stateless.co/hal_specification.html

我已经尝试了很多东西,但无济于事.例如,我已将Accept和Content-type标头设置为"application/json"而不是"application/hal + json",但我仍然收到带有超链接的JSON内容.

例如,我想得到类似的东西:

{
"name" : "Foo",
"street" : "street Bar",
"streetNumber" : 2,
"streetLetter" : "b",
"postCode" : "D-1253",
"town" : "Munchen",
"country" : "Germany",
"phone" : "+34 4410122000",
"vat" : "000000001",
"employees" : 225,
"sector" : {
     "description" : "Marketing",
     "average profit": 545656665,
     "average employees": 75,
     "average profit per employee": 4556
     }
}
Run Code Online (Sandbox Code Playgroud)

代替:

{
"name" : "Foo",
"street" : "street Bar",
"streetNumber" : 2,
"streetLetter" : "b",
"postCode" : "D-1253",
"town" …
Run Code Online (Sandbox Code Playgroud)

rest json spring-data spring-data-jpa spring-data-rest

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

Spring CrudRepository异常

我有这个Spring Data CrudRepository来处理数据库上的CRUD操作.

@Repository
public interface IUserRepository extends CrudRepository<User, String> {

}
Run Code Online (Sandbox Code Playgroud)

User是我的数据库的用户表的实体.CrudRepository将以下操作添加到存储库:

  • delete(String ID)
  • findOne(String ID)
  • save(User user)

如文档中所述IllegalArgumentException,如果给定的id为null ,则delete和find操作抛出,而save操作不会抛出任何异常.

问题是CrudRepository的javadoc没有提到这些操作抛出的其他异常.例如,如果DB中不存在提供的ID ,则不会告诉delete(String ID)操作抛出该操作EmptyResultDataAccessException.

在save(User user)操作的javadoc中,如果插入一个破坏一个数据完整性约束的新用户(在唯一字段和外键上),则不清楚抛出哪些异常.此外,它不会警告您是否正在编写新用户或现有用户:它只是创建一个新用户或覆盖(如果存在)(因此它是一个插入+更新操作).

在企业应用程序中,我应该能够捕获操作可以抛出的每个可抛出的异常,我应该在操作的javadoc中读到它.

您是否知道有关CrudRepository异常的任何明确文档?

谢谢

java spring spring-data

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

Org.Hibernate.AnnotationException:没有为实体指定的标识符我的表中没有id

我正在使用数据库中的表,并且该表没有主键或具有可作为主键的唯一值的正确列,我没有权限来更改该表.

我该怎么办?我尝试将@id注释放在一个随机列中并且它有效,但我不知道这是否会在以后带来任何麻烦.我能做什么?

我的课

@Entity
@Table(name="my_table")
public class TheTable {
@Column (name="name", nullable=false)
    private String name;

    @Id <--- I just put this id in this random column but this column should not be a id column
    @Column (name="anyfield", nullable=false)
    private String anyfield;
}
Run Code Online (Sandbox Code Playgroud)

java hibernate jpa spring-mvc spring-data

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

在Spring中将List转换为Page

我试图在春天将列表转换为页面.我用它转换了它

new PageImpl(users,pageable,users.size());

但现在我有排序和分页本身的问题.当我尝试传递大小和页面时,分页不起作用.

这是我正在使用的代码.

我的控制器

    public ResponseEntity<User> getUsersByProgramId(
        @RequestParam(name = "programId", required = true) Integer programId Pageable pageable) {

    List<User> users = userService.findAllByProgramId(programId);
    Page<User> pages = new PageImpl<User>(users, pageable, users.size());

    return new ResponseEntity<>(pages, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)

这是我的用户回购

public interface UserRepo extends JpaRepository<User, Integer>{

public List<User> findAllByProgramId(Integer programId);
Run Code Online (Sandbox Code Playgroud)

这是我的服务

    public List<User> findAllByProgramId(Integer programId);
Run Code Online (Sandbox Code Playgroud)

java spring pagination list spring-data

37
推荐指数
7
解决办法
5万
查看次数

如何在Spring-data-rest中将Page <ObjectEntity>映射到Page <ObjectDTO>

当我点击数据库时,PagingAndSortingRepository.findAll(Pageable)我得到了Page<ObjectEntity>.但是,我想将DTO暴露给客户端而不是实体.我可以通过将实体注入到它的构造函数中来创建DTO,但是如何将Page对象中的实体映射到DTO?根据spring文档,Page提供了只读操作.

另外,Page.map不可能,因为我们不支持java 8.如何手动创建带有映射对象的新页面?

java spring spring-mvc spring-data spring-data-rest

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

为什么RestTemplate没有将响应表示绑定到PagedResources?

我使用spring-data-rest将实体公开为(分页)休息资源.一切正常,但当我通过请求数据时RestTemplate,我得到一个无用的HATEOAS JSON(我没有要求).JSON似乎是一个PagedResources.我可以忍受,但JSON没有正确转换为对象.content里面没有.

库:

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long>
{
    List<Person> findByLastName(@Param("name") String name);
}
Run Code Online (Sandbox Code Playgroud)

客户:

public List<Person> getPersons()
{
    RestTemplate rt = new RestTemplate();
    System.out.println(rt.getForObject(URL, PagedResources.class).getContent().size());
    System.out.println(rt.getForObject(URL, PagedResources.class).getLinks().size());
    System.out.println(rt.getForObject(URL, PagedResources.class).getMetadata().getTotalElements());
    return new ArrayList<Person>(rt.getForObject(URL, PagedResources.class).getContent()); // <-- empty
}
Run Code Online (Sandbox Code Playgroud)

System.out的:

0 // getContent().size()
4 // getLinks().size()
2 // getTotalElements()
Run Code Online (Sandbox Code Playgroud)

卷曲:

C:\...>curl http://localhost:8080/spring-jsf-rest/rest/people
{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/spring-jsf-rest/rest/people{?page,size,sort}",
      "templated" : true
    },
    "search" : {
      "href" …
Run Code Online (Sandbox Code Playgroud)

rest spring json spring-data spring-data-rest

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

Spring Data JPA:按示例查询?

使用Spring Data JPA可以通过示例进行查询,其中特定实体实例用作搜索条件吗?

例如(没有双关语),如果我有一个Person看起来像这样的实体:

@Entity
public class Person {
  private String firstName;
  private String lastName;
  private boolean employed;
  private LocalDate dob;
  ...
}
Run Code Online (Sandbox Code Playgroud)

我可以找到所有在1977年1月1日出生的史密斯姓氏的雇员,举个例子:

Person example = new Person();
example.setEmployed(true);
example.setLastName("Smith");
example.setDob(LocalDate.of(1977, Month.JANUARY, 1));
List<Person> foundPersons = personRepository.findByExample(example);
Run Code Online (Sandbox Code Playgroud)

java spring spring-data spring-data-jpa

36
推荐指数
3
解决办法
5万
查看次数