Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using Hibernate for powerful object persistence and querying


In this recipe, you will learn how to use Hibernate with Spring. We'll use a MySQL database.

Getting ready

In this recipe, we'll use a MySQL database with the user table:

CREATE TABLE user (
  id int NOT NULL AUTO_INCREMENT,
  first_name text,
  age int DEFAULT NULL,
  PRIMARY KEY (id)
);

We'll use this corresponding JPA-annotated domain class:

@Entity
@Table(name = "user")
public class User {

  @Id
  @GeneratedValue
  private Long id;
  
  @Column(name = "first_name")
  private String firstName;
  
  private Integer age;
  
  // getters and setters.. 

For more information about the Java Persistence API (JPA), go to: http://docs.oracle.com/javaee/6/tutorial/doc/bnbpz.html.

How to do it…

Here are the steps to integrate Hibernate with Spring:

  1. Add the Maven dependencies for Spring ORM, Hibernate, and the JDBC driver for MySQL in pom.xml:

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm...