Spring+JPA with Hibernate

This is a sample of using Spring 2.5 with JPA provided by Hibernate 3.2.

This is the model class Trip.java


package sample.model;import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Column;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;import java.util.Date;

@Entity
@Table(name = "trips")
@NamedQueries({
@NamedQuery(name="Trip.allTrips", query="from Trip")
})
public class Trip  {

@Id
@GeneratedValue
private Long id;

@Column(length = 30)
private String tripName;
@Column(length = 3)
private int duration;
@Column(length = 20)
private Date startDate;
@Column(length = 500)
private String description;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

/**
* @return the tripName
*/
public String getTripName() {
return tripName;
}

/**
* @param tripName the tripName to set
*/
public void setTripName(String tripName) {
this.tripName = tripName;
}

/**
* @return the duration
*/
public int getDuration() {
return duration;
}

/**
* @param duration the duration to set
*/
public void setDuration(int duration) {
this.duration = duration;
}

/**
* @return the startDate
*/
public Date getStartDate() {
return startDate;
}

/**
* @param startDate the startDate to set
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}

/**
* @return the description
*/
public String getDescription() {
return description;
}

/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}

}

The service implmentation TripServiceImpl.java

package sample.service;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import sample.model.Trip;

@Transactional
public class TripServiceImpl implements TripService {

private EntityManager em;
/**
* @return the em
*/
public EntityManager getEntityManager() {
return em;
}

/**
* @param em
*            the em to set
*/
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}

public Trip find(int id) {
return em.find(Trip.class, id);
}

@SuppressWarnings("unchecked")
public List<Trip> findAll() {
Query query = getEntityManager().createQuery("select t from trip ");
return query.getResultList();
}

@SuppressWarnings("unchecked")
public List<Trip> findAllTrips() {
List resultList = getEntityManager().createNamedQuery("Trip.allTrips")
.getResultList();
final List<Trip> trips = resultList;
return trips;
}

public void remove(int id) {
Trip trip = find(id);
if (trip != null)
em.remove(trip);

}

public void save(Trip trip) {
if (trip.getId() == null)
// create new
em.persist(trip);
else
// update
em.merge(trip);

}

}

The spring application context - spring.xml


 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"
default-autowire="byName">


 		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
 			
 				class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">


 				
 		class="org.springframework.jdbc.datasource.DriverManagerDataSource">



	
 		class="org.springframework.orm.jpa.JpaTransactionManager" />

The test client TripTest.java (not JUnit test but a client to display the values)


package sample.test;

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import sample.service.*;
import sample.model.*;

public class TripTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"sample/spring.xml");

TripService service = (TripService) ctx.getBean("tripService");

List<Trip> allTrips = service.findAllTrips();
System.out.println("No. of trips is " + allTrips.size());
System.out.println("First trip name is "
+ allTrips.get(0).getTripName());
}
}

This entry was posted on Wednesday, October 31st, 2007 at 1:34 pm and is filed under Java. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply