JDBC Problems - Unitec Institute of Technology

Download Report

Transcript JDBC Problems - Unitec Institute of Technology

ENTERPRISE JAVA
Spring and Java Persistence Architecture
JDBC Problems





Lots of hand coding needed to setup SQL
Lots of dangerous code inside of try-catch-finally
Massive duplication of effort
Extra queries for other
parts of the car. For
Tied to specific database
each car!
Relationships are hard
 N+1
SELECT * FROM Cars;
SELECT * FROM Wheel WHERE CarId = ?
select problem
 Parent-child update / delete issues

Lots of nasty hand coded build SQL statement code
2
Hibernate/JPA

Object Relational Mapping
 Generates
the code from the database
 Generates the database from the code

Maps all sorts of associations
 One-to-One
 Many-to-One
 Many-to-Many


Classes are simple POJOs with annotations
Can also define using XML
3
Best Practice





Design a good data model first (ER Diagram)
Replicate data model in Spring/JPA
Keep Controller and Repository code separate
One JPA class per table
Even easier than JDBCTemplate and less code!
4
Annotations
@Entity
@Table(name="Book")

Annotations for defining a table
@Id
@GeneratedValue
@Column(name="book_id")

Annotations for defining a primary key

http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/
5
@Entity
@Table(name="Book")
public class Book implements Serializable {
private Long bookId;
// ...
@Id
@GeneratedValue
@Column(name="book_id")
public Long getBookId() {
return bookId;
}
@Column(name="title")
public String getTitle() {
return title;
}
CrudRepository
@Repository
public interface BookRepository extends CrudRepository<Book, Long>
{
Iterable<Book> findByTitle(String title);
Iterable<Book> findByAuthor(String author);
Iterable<Book> findByGenre(String genre);
Iterable<Book> findByTitleAndAuthorAndGenre(String title,String author,String genre);
Iterable<Book> findByTitleIgnoreCaseOrAuthorIgnoreCaseOrGenreIgnoreCase(String title,String author,String genre);
}



Auto generated code created by Spring to handle:
 Create
 Read
 Update
 Delete operations
Can define extra find methods to customise queries, behaviour defined by method name
We do not need to actually implement the BookRepository interface
7
CrudRepository
@Controller
public class BookController
{
@Autowired
private BookRepository bookRepo;
@RequestMapping(method = RequestMethod.GET, value = "/books")
public String home(Map<String, Object> model)
{
Iterable<Book> books = bookRepo.findAll();
model.put("books", books);
return "home";
}
@RequestMapping(method = RequestMethod.POST, value = "/books")
public String save(Book book)
{
bookRepo.save(book);
return "redirect:/books";
}
8
CrudRepository


Gives us a lot for free
Saves us a lot of time
 Less
development
 Less code
 Less debugging


Much easier than using JPA directly
See link for more information on various types of
query than can be setup:

http://docs.spring.io/springdata/jpa/docs/current/reference/html/#repositories.query-methods
9
Hibernate Criteria


Programmatically add criteria to a query using
Java code
Create a new Criteria object using a Hibernate
Session for the Entity that you are interested in


Add one or more Restrictions to the criteria


Criteria criteria = session
.createCriteria(Book.class);
criteria.add(Restrictions.eq("bookId", id));
Return list of matching criteria using

criteria.list();
10
Session session =
HibernateUtil.getSessionFactory().
getCurrentSession();
session.beginTransaction();
LinkedList<Book> books = new LinkedList<Book>();
try {
Criteria criteria =
session.createCriteria(Book.class);
criteria.add(Restrictions.eq("bookId", id));
books.addAll((List<Book>)criteria.list());
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
Queries




Use the @Query annotation in your repository
interface file.
Create a completely customised adhoc query
Can also define a @NamedQuery on model object
Define the query in JPQL and also define the
method:
@Query("SELECT b FROM Book b WHERE b.title like :title")
public List<Book> findTitleWildcard(@Param("title") String title);
12
JPA / Hibernate Queries


Lets you run adhoc queries that understand
inheritance and polymorphism
Uses HQL and you can also run SQL on the
database directly
Query query = session.createQuery
("from Book b where b.genre = :genre");
query.setString("genre", genre);
query.list();

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html
13