Browse Source

Extend BookRepository interface; implement updateWithoutPrice method

Signed-off-by: Pekka Helenius <fincer89@hotmail.com>
v0.0.3-alpha
Pekka Helenius 4 years ago
parent
commit
28d42eff87
3 changed files with 71 additions and 2 deletions
  1. +2
    -2
      bookstore/src/main/java/com/fjordtek/bookstore/model/book/BookRepository.java
  2. +12
    -0
      bookstore/src/main/java/com/fjordtek/bookstore/model/book/BookRepositoryCustom.java
  3. +57
    -0
      bookstore/src/main/java/com/fjordtek/bookstore/model/book/BookRepositoryImpl.java

+ 2
- 2
bookstore/src/main/java/com/fjordtek/bookstore/model/book/BookRepository.java View File

@ -24,7 +24,7 @@ import org.springframework.data.rest.core.annotation.RestResource;
itemResourceRel = "booklist",
exported = true
)
public interface BookRepository extends CrudRepository<Book, Long> {
public interface BookRepository extends CrudRepository<Book, Long>, BookRepositoryCustom {
@Override
//@RestResource(exported = false)
@ -50,7 +50,7 @@ public interface BookRepository extends CrudRepository<Book, Long> {
/*
* We need to override native delete method due to book hash id usage.
* This is a native query, do not unnecessarily validate it.
* This is a native HQL query, do not unnecessarily validate it.
*/
@Override
@Modifying


+ 12
- 0
bookstore/src/main/java/com/fjordtek/bookstore/model/book/BookRepositoryCustom.java View File

@ -0,0 +1,12 @@
package com.fjordtek.bookstore.model.book;
/**
*
* @author Pekka Helenius
*/
public interface BookRepositoryCustom {
void updateWithoutPrice(Book book);
}

+ 57
- 0
bookstore/src/main/java/com/fjordtek/bookstore/model/book/BookRepositoryImpl.java View File

@ -0,0 +1,57 @@
package com.fjordtek.bookstore.model.book;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
/**
*
* @author Pekka Helenius
*/
@Transactional
public class BookRepositoryImpl implements BookRepositoryCustom {
@PersistenceContext
EntityManager entityManager;
/*
* Selective update
* Hibernate takes care of entityManager transactions (begin, commit, rollback, close, etc.)
*/
@Override
public void updateWithoutPrice(Book book) {
try {
/*
* Book: refers to entity class, not table name!
*/
Query query = entityManager.createQuery(
"UPDATE Book SET"
+ " author_id = :author,"
+ " category_id = :category,"
+ " isbn = :isbn,"
+ " title = :title,"
+ " year = :year"
+ " WHERE id = :id"
);
query.setParameter("author", book.getAuthor().getId());
query.setParameter("category", book.getCategory().getId());
query.setParameter("isbn", book.getIsbn());
query.setParameter("title", book.getTitle());
query.setParameter("year", book.getYear());
query.setParameter("id", book.getId());
query.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}

Loading…
Cancel
Save