0

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;
	}
	
	
}

My author 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.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;
	}
	
}

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;
	}
	
}
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);
	}

1 Answer 1

0

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.

The relevant JPQL operator is:

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

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

For example:

'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'.

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);
}

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

4
  • i did what you told above, error is coming :object references an unsaved transient instance - save the transient instance before flushing: golive.data.Author
    – ratnesh
    Jun 18, 2015 at 11:38
  • How do you create/get the Author you are passing as parameter? Note the bold comment at the bottom of the answer.
    – Alan Hay
    Jun 18, 2015 at 11:39
  • i just now added my method of requestmapping once see if its correct
    – ratnesh
    Jun 18, 2015 at 11:41
  • No, retrieve an Author from the database as clearly stated in the answer. So create an Author Repository definition just like the above but for Authors and use the inherited findOne(..) method to get the existing persistent instance.
    – Alan Hay
    Jun 18, 2015 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.