如何使用Spring数据获取数据 [英] How to Fetch Data using Spring Data

查看:80
本文介绍了如何使用Spring数据获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我想创建一个扩展JpaRepository的存储库并获取结果,而无需编写实际的查询, 在我的示例中,我有2个表Book and Author(按多对多关系映射),假设我想按特定的author_id来获取图书清单,因为在我的图书实体中,我没有任何名为author_id的字段,所以我将如何使用JPARepository来获取结果,而无需编写实际的查询. 我正在做这样的事情:我创建了一个包含Book和Author对象的bookDTO,并且创建了扩展JpaRepository的bookDTORepository并调用了List<Book> findByAuthor_Id(Integer id);,但是它的抛出错误为:Not an managed type: class golive.data.bookdto我的书类是

Hey i want to create a repository extending JpaRepository and fetch result without writing actual query, In my example i have 2 tables Book and Author mapped by many to many relationship, suppose i want to fetch list of books by a particular author_id, since in my book entity, i don't have any field named author_id, so how will i use JPARepository to fetch results without writing actual query. I was doing something like this: I created a bookDTO which contain object of Book and Author, and i created bookDTORepository extending JpaRepository and was calling List<Book> findByAuthor_Id(Integer id); , but its throwing error as: Not an managed type: class golive.data.bookdto My book class is

package golive.data;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sun.istack.internal.NotNull;

@Entity
@Table(name="book")
public class Book implements java.io.Serializable{

	@Id
	@GeneratedValue
	private Integer id;
	
	@NotNull
	@Column(name="name")
	private String name;


	@ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY)
	@JoinTable(name = "writes", joinColumns = { @JoinColumn(name = "book_id") }, inverseJoinColumns = { @JoinColumn(name = "author_id") })
	private Set<Author> authors = new HashSet<Author>(); 


	public Set<Author> getAuthors() {
		return authors;
	}

	public Integer getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public void setAuthors(Set<Author> authors) {
		this.authors = authors;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	
}

我的作者班是

package golive.data;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sun.istack.internal.NotNull;

@Entity
@Table(name="author")
public class Author implements java.io.Serializable{

	@Id
	@GeneratedValue
	@Column(name="id")
	private Integer Id;
	
	@NotNull
	@Column(name="name")
	private String name;


	public Integer getId() {
		return Id;
	}

	public String getName() {
		return name;
	}



	public void setId(Integer id) {
		Id = id;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}

我的bookdto班是

My bookdto class is

package golive.data;

public class bookdto {

	private Book book;
	private Author author;
	public Book getBook() {
		return book;
	}
	public void setBook(Book book) {
		this.book = book;
	}
	public Author getAuthor() {
		return author;
	}
	public void setAuthor(Author author) {
		this.author = author;
	}
	
}

而我的bookDTORepository是:

and my bookDTORepository is :

package golive.data;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

public interface bookDTORepository extends JpaRepository<bookdto, Book> {
	
	List<Book> findByAuthor_Id(Integer id);
	
}

我的读书控制器方法是:

My book controller method, i added:

	@RequestMapping(value = "/listbyauthor", method = RequestMethod.POST, produces = "application/json")
	public ResponseEntity<List<Book>> getBookByAuthorId(@RequestBody Author author,HttpServletResponse response) {
		try {
			Author temp = new Author();
			temp.setId(author.getId());
			temp.setName(author.getName());
			return new ResponseEntity<>(bookRepository.findByAuthor(temp), HttpStatus.OK);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseEntity<>(HttpStatus.NO_CONTENT);
	}

推荐答案

您要查找特定作者的所有书籍,因此,在给定作者的情况下,检索其作者集中包含指定作者的所有书籍.

You want to find all books for a specific author so, given an Author, retrieve all Books whose set of Authors contains the specified Author.

相关的JPQL运算符为:

The relevant JPQL operator is:

http://www.objectdb.com/java/jpa/query/jpql/collection#NOT_MEMBER_OF_

[NOT] MEMBER [OF] [NOT] MEMBER OF运算符检查是否指定了 元素包含在指定的持久性收集字段中.

[NOT] MEMBER [OF] The [NOT] MEMBER OF operator checks if a specified element is contained in a specified persistent collection field.

例如:

c.languages的英语"成员为TRUE 如果不是,则为英语",否则为FALSE. 英语"不是c.language的成员是 如果语言不包含英语",则为TRUE.

'English' MEMBER OF c.languages is TRUE if languages contains 'English' and FALSE if not. 'English' NOT MEMBER OF c.languages is TRUE if languages does not contain 'English'.

您可能(也可能不知道)意识到,您正在使用Spring Data,它可以根据方法名称为您派生一些查询.但是,文档中并未提及对[NOT] MEMBER [OF]运算符的支持:

As you may (or may not) be aware, you are using Spring Data which can derive some queries for you depending on method name. The docs do not however mention support for the [NOT] MEMBER [OF] operator:

http ://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation

因此,您需要向存储库中添加一个自定义查询方法,该方法类似于:

You will therefore need to add a custom query method to your repository which will look something like:

public interface BookRepository extends JpaRepository<Book, Integer> {

    @Query("select b from Book b where ?1 MEMBER OF b.authors")
    List<Book> findByAuthor(Author author);
}

作为参数传递的Author是从数据库(通过您的AuthorRepository)检索的持久实例.

and where the Author passed as a parameter is a persistent instance retrieved from the Database (via your AuthorRepository).

这篇关于如何使用Spring数据获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆