我是Spring JPA的新手.我有一个名为Product的模型.我正在尝试编写一个api终点来获取products表的最近记录.
public static interface Repository extends PagingAndSortingRepository<Product, Long>
{
List findTop2ByOrderByIdDesc();
}
Run Code Online (Sandbox Code Playgroud)
当我运行我的应用程序HAL浏览器 http:// localhost:8080/api/v1/products/search/findTop2ByOrderByIdDesc
我收到的错误是
{
"timestamp": 1440573947629,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.IncorrectResultSizeDataAccessException",
"message": "result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements",
"path": "/api/v1/products/search/findTop2ByOrderByIdDesc"
}
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题.好心提醒
我想在存储库接口中执行类似的操作(在Spring Data JPA中):
interface myRepository extends JpaRepository<A, Long> {
@Query("select a from A a where a.x = :x")
A findFirstBySomeCondition(int x);
}
Run Code Online (Sandbox Code Playgroud)
但我只需要第一个结果.(编辑:实际查询条件非常复杂,所以我更喜欢使用@Query代替findFirst或findTop ...)
我不想使用标准api,因为它很冗长.
我不想使用本机查询,因为我将不得不手动编写查询字符串.
那么,考虑到上面的限制要求,是否还有解决方案?
谢谢!
我要执行的操作如下:我有一些复杂的SQL(使用SUM(distance)distanceSum作为返回列的标识符),该SQL返回一些应该解析为类的值(仅包含这些列所需的值) 。但是,我只需要结果在内存中,而不是实体。我已经尝试创建一个存储库,以使用本机= true的@Query注释执行SQL。但是,存储库无法自动装配,可能是因为存储库仅用于实体。
因此,有什么办法可以调整非实体的存储库,或者有什么其他方法可以使我执行SQL并将结果自动解析为对象。
我怎样才能使用jpa findBy和两个不同数据类型的参数?一些代码如:
@Entity
@Data
@Cacheable
@Table(name = "user")
public class UserEntity {
@Id
@GeneratedValue
private int id;
@Column
private String username;
}
public interface UserRepository extends JpaRepository<UserEntity, Integer> {
UserEntity findByIdOrUsername(String idOrUsername);
}
Run Code Online (Sandbox Code Playgroud)
当启动应用程序时,出现了一些错误:init方法的调用失败; 嵌套异常是java.util.NoSuchElementException
2016-01-15 17:00:47.294 ERROR 36266 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private tv.acfun.cloud.service.user.repository.UserRepository tv.acfun.cloud.service.user.controller.UserController.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': …Run Code Online (Sandbox Code Playgroud) 我正在使用spring Pageable数据和对象。当按在数据库中可以具有相同值的字段进行排序时,更改页面会检索错误的结果。
我正在尝试使用HandlerInterceptorAdapter通过id添加默认订单,如下所示:
我的拦截器:
public class OrderByIdWebArgumentResolver extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
HandlerMethod hm= (HandlerMethod) handler;
Method method = hm.getMethod();
OrderById orderById = method.getAnnotation(OrderById.class);
if (orderById != null) {
for (MethodParameter parametro : hm.getMethodParameters()) {
if (parametro.getGenericParameterType().equals(Pageable.class)) {
Map<String, String[]> parameters = request.getParameterMap();
String[] sortById = new String[2];
sortById[0] = "id";
sortById[0] = "desc";
parameters.put("sort", sortById);
}
}
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
我的控制器:
@OrderById
@RequestMapping(value = "/print", method = RequestMethod.GET)
public …Run Code Online (Sandbox Code Playgroud) 我在应用程序上使用Spring Boot(1.3.3)和基于注释的/ JavaConfig配置.我有以下存储库接口:
@RepositoryRestResource(collectionResourceRel = "something", path = "something")
public interface SomethingRepository
extends CrudRepository<SomethingRepository, Long> {
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是覆盖生成的存储库代理中的某些方法的行为.我发现这样做是基于什么文档建议添加新的自定义方法的唯一方法(参见:添加自定义行为,单库),所以我定义如下界面:
public interface SomethingRepositoryCustom {
Something findOne(Long id);
}
Run Code Online (Sandbox Code Playgroud)
...并添加相应的实现:
public SomethingRepositoryImpl extends SimpleJpaRepository<Something, Long>
implements SomethingRepositoryCustom {
public SomethingRepositoryImpl(<Something> domainClass, EntityManager em) {
super(domainClass, em);
this.entityManager = em;
}
@Override
public Something findOne(Long id) {
System.out.println("custom find one");
// do whatever I want and then fetch the object
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我启动应用程序,我会收到以下错误:
... org.springframework.beans.BeanInstantiationException:无法实例[com.dummy.repositories.SomethingRepositoryImpl]:没有发现默认的构造函数; 嵌套的例外是java.lang.NoSuchMethodException:com.dummy.repositories.SomethingRepositoryImpl()...
问题: 如何解决BeanInstantiationException?我假设我需要声明一个存储库工厂bean,但我不知道如何覆盖Spring …
我使用变量set in 为正确设置REST URL的@RestController所有@Entity对象创建了一个对象,但是它没有使用变量.spring.data.rest.base-pathapplication.peroperties/api@RequestMapping("someEndpoint")
例
对于@Entity类User,REST端点位于:
`http://localhost:8081/api/users'
Run Code Online (Sandbox Code Playgroud)
但是当我尝试访问时someEndpoint:
'http://localhost:8081/api/someEndpoint'
Run Code Online (Sandbox Code Playgroud)
我收到的答复是:
响应状态
HTTP/1.1 404 Not Found
Run Code Online (Sandbox Code Playgroud)
身体
"timestamp":1461267817272,"status":404,"error":"Not Found","message":"No message available","path":"/api/someEndpoint"}
Run Code Online (Sandbox Code Playgroud)
相反,REST服务的端点位于
'http://localhost:8081/someEndpoint'
Run Code Online (Sandbox Code Playgroud)
响应:
HTTP/1.1 200 OK
Run Code Online (Sandbox Code Playgroud)
控制器类
@RestController
public class HomeController {
@RequestMapping(value = "/")
public String index() {
return "index";
}
@RequestMapping("someEndpoint")
public Stuff runSomething(
@RequestParam(value = "id", required = true) String id)
Run Code Online (Sandbox Code Playgroud)
我的配置中缺少什么?
谢谢
我正在尝试在扩展CrudRepository接口的接口中创建自定义查询.不幸的是,每次我收到java.lang.AbstractMethodError时出于某种原因.请参阅下面的完整堆栈跟踪.
据我所知,问题是Spring框架应该"神奇地"为我的方法声明创建一个实现,但由于某种原因它没有成功.
存储库界面:
public interface PresentationRepository extends CrudRepository<Presentation, Integer> {
Iterable<Presentation> findAll(Sort sort);
Page<Presentation> findAll(Pageable pageable);
List<Presentation> findByTitle(String title); // the problematic line
}
Run Code Online (Sandbox Code Playgroud)
演示实体课程:
@Entity
@Table(name = "presentation")
public class Presentation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "presentation_id")
Integer id;
String title;
String logo;
@Column(name = "length")
Integer interval;
@Column(name = "pages")
Integer pageCount;
Date created;
Date modified;
Date approved;
Date published;
Date deleted;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "presentation_filters",
joinColumns = @JoinColumn(name = "presentation_id"),
inverseJoinColumns = …Run Code Online (Sandbox Code Playgroud) 我开始玩Spring Boot,作为其中的一部分,我想创建一个内存DB来与应用程序一起工作和引导程序.
鉴于下面的配置/代码我在启动日志中没有错误并且可以访问应用程序,所以它确实启动(我得到关于不存在的对象的模板错误),但是在调用时我没有从DAO获得任何数据findAll()(或者如果我尝试调用findById(int)).
所以虽然看起来一切正常(日志中没有错误,日志显示它找到sql来创建架构广告尝试运行data.sql语句)当我尝试通过DAO访问数据时我没有得到异常,但没有返回数据.
关于代码可能有问题的任何想法或观察?
我已将Spring Data/H2添加到我的pom中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
Run Code Online (Sandbox Code Playgroud)
春天DAO:
public interface PersonDao extends CrudRepository<Person, Integer> {
}
Run Code Online (Sandbox Code Playgroud)
application.properties中的数据库道具:
server.contextPath=/
server.port=8080
spring.mvc.view.suffix=.ftl
datasource.mine.jdbcUrl=jdbc:h2:tcp://localhost/mem:clubmanagement
datasource.mine.user=sa
datasource.mine.password=
datasource.mine.poolSize=30
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=DEBUG
spring.jpa.hibernate.ddl-auto=create
Run Code Online (Sandbox Code Playgroud)
我的服务:
@Service
public class MemberServiceImpl implements MemberService {
@Autowired
PersonDao dao;
@Override
public Optional<ClubMember> getClubMember(int id) {
Person dbPerson = dao.findOne(id);
if(dbPerson == null) {
return Optional.empty();
}
return Optional.of(fromEntity(dbPerson));
}
@Override
public List<ClubMember> allMembers() {
Iterable<Person> people = dao.findAll();
List<ClubMember> members = new ArrayList<>(); …Run Code Online (Sandbox Code Playgroud) 在spring数据中,elasticsearch一个模型类/实体表示或映射到索引和类型.
例如: -
@Document(indexName = "myindex",type="mytype")
public class DocumentModel {
......
}
Run Code Online (Sandbox Code Playgroud)
我有一个用例,我应该在具有相同结构的不同es索引中索引数据.如果是这种情况,我怎样才能用这个模型类表示所有这些索引?
spring-data ×10
spring ×9
java ×3
spring-boot ×3
spring-mvc ×2
h2 ×1
hal ×1
hibernate ×1
jpa ×1
jpql ×1
rest ×1