SyntaxHighlighter

Showing posts with label Hibernate 4. Show all posts
Showing posts with label Hibernate 4. Show all posts

Friday, April 5, 2013

Spring Integration JPA and REST

Spring Integration JPA and REST


here's a little sample project i put together to illustrate how to expose JPA objects via REST using Spring Integration.  it's a bit rough but it does the following;
- PUT a new entity
- GET an entity by id
- GET all entities

here's the entity;

package de.incompleteco.spring.jpa.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="simple_entity")
public class SimpleEntity implements Serializable {

 private static final long serialVersionUID = 1l;

 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private Long id;
 
 @Column
 private String stuff;

 public Long getId() {
  return id;
 }

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

 public String getStuff() {
  return stuff;
 }

 public void setStuff(String stuff) {
  this.stuff = stuff;
 }

 @Override
 public String toString() {
  return "SimpleEntity [id=" + id + ", stuff=" + stuff + "]";
 }
 
}


here's the entity manager factory;



 
  
  
  
   
    
   
  
 
 
 
  

  
   
   
  

 



here's the Spring Integration for the JPA service



 
 
 
 
  
 
 
 
 
 
 
   
 

 
 
 
 
   
 
 



here's the Spring Integration for the HTTP endpoint



 
 
 
 
 

 
  
  
 

 
 
 
 
  
  
 
 
 
 
 
  
  
  
  
 

 
 
 

 




and here's a test showing it all

package de.incompleteco.spring.jpa;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

import javax.annotation.Resource;

import org.codehaus.jackson.map.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.context.WebApplicationContext;

import de.incompleteco.spring.jpa.domain.SimpleEntity;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({"classpath:/META-INF/spring/*-context.xml"})
@ActiveProfiles("junit")
public class IntegrationTest {

 @Resource
 private WebApplicationContext context;
 
 private ObjectMapper mapper;
 
 private MockMvc mvc;
 
 @Before
 public void before() throws Exception {
  //setup
  mapper = new ObjectMapper();//json
  mvc = webAppContextSetup(context).build();  
 }

 @Test
 public void test() throws Exception {
  //create an object
  SimpleEntity entity = new SimpleEntity();
  entity.setStuff("hello world");
  //convert
  String json = mapper.writeValueAsString(entity);
  //execute
  MvcResult result = mvc.perform(put("/simpleEntity").contentType(MediaType.APPLICATION_JSON).content(json))
   .andExpect(status().isOk()).andReturn();
  //now convert back
  SimpleEntity resultEntity = mapper.readValue(result.getResponse().getContentAsByteArray(), SimpleEntity.class);
  //now check
  assertTrue(resultEntity.getId() > 0);
  assertEquals(entity.getStuff(),resultEntity.getStuff());
  //retrieve by the id
  result = mvc.perform(get("/simpleEntity").param("id", resultEntity.getId().toString()))
   .andExpect(status().isOk()).andReturn();
  //now convert
  SimpleEntity retrievedEntity = mapper.readValue(result.getResponse().getContentAsByteArray(), SimpleEntity.class);
  //now check
  assertEquals(entity.getStuff(),retrievedEntity.getStuff());
  //retrieve all
  result = mvc.perform(get("/simpleEntity"))
    .andExpect(status().isOk()).andReturn();
  //now it *should* be an array of SimpleEntity
  SimpleEntity[] entities = mapper.readValue(result.getResponse().getContentAsByteArray(),SimpleEntity[].class);
  //test
  assertNotNull(entities);
  assertTrue(entities.length > 0);
  
 }
}


if you want the code, it's here; https://github.com/incomplete-code/spring-integration-jpa

Friday, March 29, 2013

JPA Versioning - Hibernate Envers


Hibernate Envers and a HashMap to Long Exception

a frequent exception i was hitting recently when trying to implement Hibernate Envers was a confusing one about problems casting a HashMap to a Long.  after digging around a bit i found that i had a field in my entity that was called 'originalId'.  thanks to a bit of searching on the Hibernate forum, this was identified as the cause. presto chango - field is renamed and problem goes away.

tl;dr - if you see the casting exception, check that you don't have 'originalId' in your entity.

Monday, November 5, 2012

Batoo and Spring Data JPA - round 1

Batoo and Spring Data JPA - round 1


with all the latest info on Batoo JPA, i've started playing with Spring Data JPA and using Batoo.  here's a little catch; Batoo expects a persistence.xml.  if you're using Spring Data XMLless, no joy.  it tries to parse it anyway and bombs.

this was discovered whilst trying to roll a VendorAdapter for the LocalContainerEntityManagerFactory.  am going to keep trying to work around this if possible, it looks like fun.


Monday, October 1, 2012

Hibernate 4 and WebSphere / JTA

Hibernate 4 and WebSphere / JTA


when looking through to debug some code recently i came across this...


package org.hibernate.service.jta.platform.internal;

public class WebSphereExtendedJtaPlatform extends AbstractJtaPlatform {

 ...

@Override
@SuppressWarnings( {"UnnecessaryBoxing"})
public Object getTransactionIdentifier(Transaction transaction) {

// WebSphere, however, is not a sane JEE/JTA container...

return Integer.valueOf( transaction.hashCode() );

}


 ...
}


brilliant!

Saturday, September 29, 2012

Spring LocalContainerEntityManagerFactoryBean, packagesToScan and JTA

Spring LocalContainerEntityManagerFactoryBean, packagesToScan and JTA


here's an interesting one, Hibernate 4, Spring JPA (using LocalContainerEntityManagerFactoryBean) and JTA.  the scenario is, testing in JUnit and need to specify (and emulate) a JTA transaction. unfortunately, it's not all straight out-of-the-box, but here it is;

first, LocalContainerEntityManagerFactoryBean treats everything as a non-JTA transaction, so there's a little extra configuration to be done.  To switch it out, Spring does provide a postProcessor for the PersistenceUnit and a mutable persistent unit to it, but we have to write our own switch.  (it's pretty straight forward, but maybe we can ask the nice chaps to include it out of the box in 3.2.x?)

here's my cut - you can roll/cut & paste your own

package org.incompletecode.spring.batch.jpa;
 
import org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo;
import org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor;
 
public class JTAPersistenceUnitPostProcessor implements
  PersistenceUnitPostProcessor {
 
 @Override
 public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
  //switch the nonJTA to JTA
  pui.setJtaDataSource(pui.getNonJtaDataSource());
  pui.setNonJtaDataSource(null);
 }
 
}

and now here's a quick example of using Bitronix as your JTA provider


 
 
 
 
     
 
  
 
 
 
     
 
 
 
     
     
 
 
 
 
 
      
      
      
      
      
      
          
              jdbc:h2:mem:a;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1