简体   繁体   中英

Criteria API for Hibernate search

I have two entity classes Book(bookId,bookName) and Chapter(chapterId,chapterName). I am trying to search for all books starting with a particular prefix.I also want to search for book and corresponding chapter starting with a particular prefix.

My function:-

public List<Book> search(String bookName,String chapterName){
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Book.class);
    criteria.add(Restrictions.like("bookName",bookName+"%") );
    criteria.createAlias("chapter","chapter");
    criteria.add(Restrictions.like("chapter.chapterName", chapterName+"%"));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List<Book> books = criteria.list();
    return books;
}

When i enter both the bookName and the chapterName. It returns the corresponding book along with the chapterName. It also returns other chapterName contained in the book.I want to show only the book and its chapterName entered and not other chapterNames of the book

My entity classes:

Book.java

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

@Id
@Column(name="bookId")
@GeneratedValue
private Integer bookId;

@Column(name="bookName")
private String bookName;

@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinTable(
        name="BookChapter",
        joinColumns = @JoinColumn(name="BOOK_ID"),
        inverseJoinColumns = @JoinColumn(name="CHAPTER_ID")
)
private Set<Chapter> chapter;

public Integer getBookId() {
    return bookId;
}

public void setBookId(Integer bookId) {
    this.bookId = bookId;
}

public String getBookName() {
    return bookName;
}

public void setBookName(String bookName) {
    this.bookName = bookName;
}

public Set<Chapter> getChapter() {
    return chapter;
}

public void setChapter(Set<Chapter> chapter) {
    this.chapter = chapter;
}
}

Chapter.java

@Entity
@Table(name="chapter")
public class Chapter implements Serializable{

@Id
@Column(name="chapterId")
@GeneratedValue
private Integer chapterId;

@Column(name="chapterName")
private String chapterName;

@ManyToOne(cascade = CascadeType.ALL)
@JoinTable(
        name="BookChapter",
        joinColumns= @JoinColumn(name="CHAPTER_ID")
)
private Book book;

public Book getBook() {
    return book;
}

public void setBook(Book book) {
    this.book = book;
}

public Integer getChapterId() {
    return chapterId;
}

public void setChapterId(Integer chapterId) {
    this.chapterId = chapterId;
}

public String getChapterName() {
    return chapterName;
}

public void setChapterName(String chapterName) {
    this.chapterName = chapterName;
}

}

My service classes:- BookService.java

@Service("bookService")
@Transactional
public class BookService {

@Resource(name="sessionFactory")
private SessionFactory sessionFactory;

public List<Book> getAll(){
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("FROM Book");
    return query.list();
}



public List<Book> sortAll(){
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Book.class);
    criteria.addOrder(Order.asc("bookName"));
    return criteria.list();
}

public List<Book> Des(){
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Book.class);
    criteria.addOrder(Order.desc("bookName"));
    return criteria.list();
}

public Book get(Integer bookId){
    Session session = sessionFactory.getCurrentSession();
    return (Book)session.get(Book.class,bookId);
}

public void add(Book book) {
    Session session = sessionFactory.getCurrentSession();
    session.save(book);
}

public void delete(Integer bookId){
    Session session = sessionFactory.getCurrentSession();
    Book book = (Book)session.get(Book.class,bookId);
    session.delete(book);
}

public void edit(Book book){
    Session session = sessionFactory.getCurrentSession();
    Book book1 = (Book)session.get(Book.class,book.getBookId());

    book1.setBookName(book.getBookName());
    session.save(book1);
}

public List<Book> searchBook(String bookName){
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Book.class);
    criteria.add(Restrictions.like("bookName",bookName+"%") );
    return criteria.list();
}

public List<Book> search(String bookName,String chapterName){
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Book.class);
    criteria.add(Restrictions.like("bookName",bookName+"%") );
    criteria.createAlias("chapter","chapter");
    criteria.add(Restrictions.like("chapter.chapterName", chapterName+"%"));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List<Book> books = criteria.list();
    return books;
}

}

ChapterService.java

@Service("chapterService")
@Transactional
public class ChapterService {

@Resource(name="sessionFactory")
private SessionFactory sessionFactory;

public List<Chapter> getAll(Integer bookId){
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("FROM Book as b WHERE b.id="+bookId);
    Book book = (Book)query.uniqueResult();
    return new ArrayList<Chapter>(book.getChapter());
}

public List<Chapter>getAll(){
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("FROM Chapter");
    return query.list();
}

public Chapter get(Integer chapterId){
    Session session = sessionFactory.getCurrentSession();
    Chapter chapter = (Chapter)session.get(Chapter.class,chapterId);
    return chapter;
}

public void add(Integer bookId,Chapter chapter){
    Session session = sessionFactory.getCurrentSession();
    session.save(chapter);

    Book book1 = (Book)session.get(Book.class,bookId);
    book1.getChapter().add(chapter);

    session.save(book1);
}

public void delete(Integer chapterId){
    Session session = sessionFactory.getCurrentSession();
    //Query query = session.createSQLQuery("DELETE FROM bookchapter"+"WHERE CHAPTER_ID="+chapterId);

    //query.executeUpdate();
    Chapter chapter = (Chapter)session.get(Chapter.class,chapterId);
    session.delete(chapter);
}

public void edit(Chapter chapter){
    Session session = sessionFactory.getCurrentSession();
    Chapter chapter1 = (Chapter)session.get(Chapter.class,chapter.getChapterId());

    chapter1.setChapterName(chapter.getChapterName());
    session.save(chapter1);
}



}

My Controller classes

@Controller
@RequestMapping("/chapter")
public class ChapterController {

@Resource(name="chapterService")
private ChapterService chapterService;

@RequestMapping(value="/add",method=RequestMethod.GET)
public String getAdd(@RequestParam("id")Integer bookId,Model model){

    Chapter chapter = new Chapter();

    model.addAttribute("bookId",bookId);
    model.addAttribute("chapterAttribute",chapter);

    return "addChapter";
}

@RequestMapping(value="/add", method = RequestMethod.POST)
public String postAdd(@RequestParam("id")Integer bookId,@ModelAttribute("chapterAttribute")Chapter chapter){

    chapterService.add(bookId, chapter);
    return "redirect:/record/list";
}

@RequestMapping(value = "/delete", method = RequestMethod.GET)
public String getDelete(@RequestParam("id") Integer chapterId) {

    chapterService.delete(chapterId);
    return "redirect:/record/list";
}


@RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEdit(@RequestParam("bid") Integer bookId,@RequestParam("cid") Integer chapterId, Model model) {

    Chapter chapter1 = chapterService.get(chapterId);

    model.addAttribute("bookId",bookId);
    model.addAttribute("chapterAttribute",chapter1);

    return "editChapter";
}

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String postEdit(@RequestParam("id") Integer chapterId,
        @ModelAttribute("chapterAttribute") Chapter chapter) {

    chapter.setChapterId(chapterId);
    chapterService.edit(chapter);

    return "redirect:/record/list";
}

}

MainController.java

@Controller
@RequestMapping("/record")
public class MainController {

@Resource(name="bookService")
private BookService bookService;

@Resource(name="chapterService")
private ChapterService chapterService;

@RequestMapping(value="/Front")
public String Front(Model model){
    return "Front";
}

@RequestMapping(value = "/list", method = RequestMethod.GET)
public String getRecords(Model model) {

    List<Book> books = bookService.getAll();

    List<BookDTO> bookDTO = new ArrayList<BookDTO>();

    for (Book book: books) {
        BookDTO dto = new BookDTO();

        dto.setBookId(book.getBookId());
        dto.setBookName(book.getBookName());

        dto.setChapter(chapterService.getAll(book.getBookId()));

        bookDTO.add(dto);
    }

    model.addAttribute("books", bookDTO);
    return "record";
}

@RequestMapping(value="/sort",method = RequestMethod.GET)
public String sortRecords(Model model){
    List<Book>books = bookService.sortAll();
    List<BookDTO> bookDTO = new ArrayList<BookDTO>();

    for(Book book:books){
        BookDTO dto = new BookDTO();
        dto.setBookId(book.getBookId());
        dto.setBookName(book.getBookName());
        dto.setChapter(chapterService.getAll(book.getBookId()));

        bookDTO.add(dto);
    }

    model.addAttribute("books",bookDTO);
    return "record";
}

@RequestMapping(value="/dsort",method = RequestMethod.GET)
public String descRecords(Model model){
    List<Book>books = bookService.Des();
    List<BookDTO> bookDTO = new ArrayList<BookDTO>();

    for(Book book:books){
        BookDTO dto = new BookDTO();
        dto.setBookId(book.getBookId());
        dto.setBookName(book.getBookName());
        dto.setChapter(chapterService.getAll(book.getBookId()));

        bookDTO.add(dto);
    }

    model.addAttribute("books",bookDTO);
    return "record";
}

@RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAdd(Model model) {

    model.addAttribute("bookAttribute", new Book());

    return "addBook";
}


@RequestMapping(value = "/add", method = RequestMethod.POST)
public String postAdd(@ModelAttribute("bookAttribute") Book book) {

    bookService.add(book);
    return "redirect:/record/list";
}


@RequestMapping(value = "/delete", method = RequestMethod.GET)
public String getDelete(@RequestParam("id") Integer bookId) {

    bookService.delete(bookId);
    return "redirect:/record/list";
}

@RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEdit(@RequestParam("id") Integer bookId, Model model) {

    Book book1 = bookService.get(bookId);
    model.addAttribute("bookAttribute",book1);

    return "editBook";
}

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String postEdit(@RequestParam("id") Integer bookId, 
                            @ModelAttribute("bookAttribute") Book book) {

    book.setBookId(bookId);
    bookService.edit(book);
    return "redirect:/record/list";
}

@RequestMapping(value="/search",method = RequestMethod.POST)
public String getSearchBook(@RequestParam("bid")String bookName,@RequestParam("cid")String chapterName,Model model){

    List<Book>books = bookService.search(bookName,chapterName);

    model.addAttribute("books",books);
    return "display";

}

}

I myself achieved all required functionality using the below function

public List<Book> search(String bookName,String chapterName){

    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Book.class);
    criteria.add(Restrictions.like("bookName",bookName+"%") );
    criteria.createAlias("chapter","chapter",Criteria.LEFT_JOIN);
    criteria.add(Restrictions.like("chapter.chapterName",chapterName+"%"));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List<Book> books = criteria.list();

    return books;       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM