Error producing xml from response body in spring - java

Hello guys so i have a bit issue. I wrote a simple rest application using spring framework. I was able to post and get the response in json but now i want to have the option of displaying both json and xml format. Now i'm getting error 406 when trying to display the format in xml. I already included the converter in dispatcher but having trouble displaying in xml format. Please i'm i missing soemthing. Also included the dependency in maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Below is my dispatcher-servlet.xml which loads the controller. :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc-annotation="http://www.springframework.org/schema/mvc"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="edu.sjsu.cmpe275.lab2.controller" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
</list>
</property>
</bean>
<mvc:annotation-driven/>
</beans>
below is my method in the controller upon entering the url when trying to produce the output in xml:
#RequestMapping(value="player/{id}", method=RequestMethod.GET, params="format=xml", produces=MediaType.APPLICATION_XML_VALUE)
#ResponseBody
public ResponseEntity<?> inXML(#PathVariable("id")long id) {
Person person = personImpl.findById(id);
if(person!=null){
return new ResponseEntity<Person>(person, HttpStatus.OK);
}
else
return new ResponseEntity<String>("Id doesn't exist", HttpStatus.NOT_FOUND);
}
Person POJO:
public class Person {
#Id
#Column(name="person_Id")
#GeneratedValue
private long id;
#Column(unique = true)
private String email;
private String first_name, last_name, description;
//#Embedded
private Address address;
#ManyToOne(cascade = CascadeType.ALL)
private Organization organization;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(name="Friends")
Collection<Person> persons = new ArrayList<Person>();
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public Person() {}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

Related

How can I get the name and id from my java bean?

I am trying to run a test function to get the name and id of my bean from the config file. I have tried everything I can think of up until now and no luck. I get about 40 lines of errors that I have no idea how to read. I am certain it is something simple but I am just not connecting the dots. How can I fix this?
package com.intraedge.spring.springcore;
class Employee {
private int id;
private String name;
// public int getId(int args) {
// id = args;
// return id;
// }
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
package com.intraedge.spring.springcore;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("config.xml");
Employee emp = (Employee)ctx.getBean("emp");
System.out.println("Name: "+emp.getName(name.value));
// System.out.println("Id: "+emp.getId(3));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean name="emp" class="com.intraedge.spring.springcore.Employee">
<property name="id">
<value>20</value>
</property>
<property name="name">
<value>Casandra</value>
</property>
</bean>
</beans>
After updating the namespaces like suggested, there was a new error relating to the getter/setter of the bean ID. I fixed it by adding in the proper getter/setter functions and removing any arguments from the function calls.
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}

Address value shows null

I have two classes Student and Address which implements IStudent ans IAddress interfaces respectively. Student class has a relationship with Address class. That is why i have declared a reference member of it.
public class Student implements IStudent {
private String code;
private String name;
#Autowired
private IAddress address;
#Override
public String getCode() {
return this.code;
}
#Override
public String getName() {
return this.name;
}
public void setCode(String code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public IAddress getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
}
and I have Address class
public class Address implements IAddress{
private String city;
private String pinCode;
private String houseNo;
private String roadName;
#Override
public String getCity() {
return this.city;
}
#Override
public String getPinCode() {
return this.pinCode;
}
#Override
public String getHouseNo() {
return this.houseNo;
}
#Override
public String getRoadName() {
return this.roadName;
}
public void setCity(String city) {
this.city = city;
}
public void setPinCode(String pinCode) {
this.pinCode = pinCode;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public void setRoadName(String roadName) {
this.roadName = roadName;
}
}
In my applicationContext.xml file i have written the following bean definitions
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
</bean>
<bean id="addressbean" class="main.Address">
<property name="houseNo" value="119/2"></property>
<property name="roadName" value="South Avenue"></property>
<property name="city" value="Delhi"></property>
<property name="pinCode" value="110005"></property>
</bean>
</beans>
When i have checked Student object after initialization of bean, name and code has assigned with setter method. But the address is not assigned. Thus it shows null value for address. I have marked address with #Autowired annotation. Can you please help?
ApplicationContext factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) factory.getBean("studentbean");
System.out.println(student.getAddress());
you need to explicitly wire to Address not IAddress since the CI only knows Address, if you want to wired
#Autowired
private Address address;
or you need to define a bean with type IAddress but make sure you do not have more than implementation or spring will get confused, if you have more than one implementation use can qualifiers to clear the ambiguity
This whole example is kind of strange but you can get rid of the #Autowired annotation and use following bean configuration instead;
<bean id="studentbean" class="main.Student">
<property name="code" value="S001"></property>
<property name="name" value="Subhabrata Mondal"></property>
<property name="address" >
<ref local="addressbean"/>
</property>
</bean>

Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/dao/InvalidDataAccessApiUsageException

I am trying to use Mongo Template with spring but it gives InvalidDataAccessApiUsageException
My Main Class is
package com.spring.mongodb.main;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.spring.mongodb.model.Person;
public class SpringDataMongoDBMain {
public static final String DB_NAME = "mydb";
public static final String PERSON_COLLECTION = "mycol";
public static final String MONGO_HOST = "localhost";
public static final int MONGO_PORT = 27017;
public static void main(String[] args) {
try{
Mongo mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
System.out.println("Connected to MongoDB");
MongoOperations mongoOps = new MongoTemplate(mongo, DB_NAME);
System.out.println("Connected to database");
Person p = new Person("100", "ABC", "GRG PQR");
mongoOps.createCollection(PERSON_COLLECTION);
mongoOps.insert(p, PERSON_COLLECTION);
}catch(Exception e){
e.printStackTrace();
}
}
}
My Model Class is:
package com.spring.mongodb.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "person")
public class Person {
#Id
private String id;
private String name;
private String address;
public Person() {
}
public Person(String i, String n, String a) {
this.id = i;
this.name = n;
this.address = a;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public String toString() {
return id + "::" + name + "::" + address;
}
}
and my Spring.xml is
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd">
<mongo:mongo host="localhost" port="27017" id="mongo" />
<mongo:db-factory dbname="mydb" mongo-ref="mongo"
id="mongoDbFactory" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<bean id="personDAO" class="com.journaldev.spring.mongodb.dao.PersonDAOImpl">
<constructor-arg name="mongoOps" ref="mongoTemplate" />
</bean>
</beans>
When I run the above code it gives following error :
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/dao/InvalidDataAccessApiUsageException
at com.spring.mongodb.main.SpringDataMongoDBMain.main(SpringDataMongoDBMain.java:21)
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.InvalidDataAccessApiUsageException
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 1 more
I have added following jars:
mongodb-driver-3.1.1.jar
mongodb-driver-core-3.1.1.jar
spring-core-4.2.3.RELEASE.jar
spring-data-mongodb-1.6.1.RELEASE.jar
spring-data-commons-core-1.4.1.RELEASE.jar
I tried debuging the code it shows error when it comes to MongoOperations object creation and terminates.What I am doing wrong??
You're missing some jars (spring-tx, spring-beans, spring-context, spring-expression, etc..)
Have a look at maven to manage your dependencies

Hibernate 4 lazy loading doesn't work

I am working on a web application using spring 3 and hibernate 4.
I am having trouble lazy-loading a set of granted permissions of a group to which a user belongs.
When a user object is retrieved from the database, its Group object doesn't have any permissions even though user.getGroup().getPermissions() is invoked explicitly.
I noticed that in debug mode, if I mouse-over the User object and then navigate to the Group object inside the User object, and then navigate to its permissions, I can see its type is shown as PersistentSet, and expanding it will load permissions properly. But in non-debug mode, permissions are never lazy-loaded. What am I missing here? Thanks in advance.
Here are the relationships among the entities:
Users have an one-to-many relationship with groups, and groups have a many-to-many relationship with permissions.
Here's the definition of the UserDaoImpl class
#Repository
#Transactional
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
private Session getSession() {
return sessionFactory.getCurrentSession();
}
#Override
public User get(String username) {
Session session = getSession();
User user = (User) session.createCriteria(User.class).add(Restrictions.eq("username", username)).uniqueResult();
Group g = user.getGroup();
// calling g.getGrantedPermissions() doesn't load any permission
Set<Permission> permissions = g.getGrantedPermissions();
return user;
}
}
Here's the definition of the Permission class
#Entity
public class Permission {
#Id
#GeneratedValue
private Long id;
#Column
private String name;
#Column
private String description;
public Permission()
{
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here's the definition of the Group class
#Entity
#Table(name="\"Group\"")
public class Group {
public static final String ROLE_VALID_USER = "ROLE_VALID_USER";
#Id
#GeneratedValue
private Long id;
#Column
private String description;
#Column
private String role;
#ManyToMany
#JoinTable(name = "granted_permission",
joinColumns = {#JoinColumn(name = "GROUP_ID", nullable = false, updatable = false) },
inverseJoinColumns = { #JoinColumn(name = "PERMISSION_ID", nullable = false, updatable = false) })
private Set<Permission> grantedPermissions;
public Group()
{
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Set<Permission> getGrantedPermissions() {
return grantedPermissions;
}
public void setGrantedPermissions(Set<Permission> grantedPermissions) {
this.grantedPermissions = grantedPermissions;
}
}
Here's the definition of the User class
#Entity
public class User {
#Id
#Column(name="USERNAME")
private String username;
#Column(name="PASSWORD")
private String password;
#Transient
private final boolean enabled = true;
#Column
private String name;
#Column(name="EMAIL")
private String email;
#Column(name="PHONE")
private String phone;
#ManyToOne
private Group group;
#ManyToOne
#JoinColumn(name="ORIGINAL_BRANCH_ID")
private Branch originalBranch;
#ManyToOne
#JoinColumn(name="ID_OF_RESPONSIBLE_BRANCH")
private Branch responsibleBranch;
public User()
{
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return group.getRole();
}
public boolean isEnabled() {
return enabled;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public Branch getOriginalBranch() {
return originalBranch;
}
public void setOriginalBranch(Branch originalBranch) {
this.originalBranch = originalBranch;
}
public Branch getResponsibleBranch() {
return responsibleBranch;
}
public void setResponsibleBranch(Branch responsibleBranch) {
this.responsibleBranch = responsibleBranch;
}
}
Here's the persistence configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<tx:annotation-driven />
<context:annotation-config />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<context:component-scan base-package="net.acme.prs" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="mysqlDataSource" />
<property name="packagesToScan" value="net.acme.prs" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQL5InnoDBDialect
</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/prs" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
</beans>
I cannot understand what is your problem because you haven't mentioned any error you encountered. If you simply found there was no SQL to fetch the grantedPermissions, it is what lazy-fetching is about: It is only fetched when it is accessed, and if it is not accessed, it won't be fetched.
The reason you see it being fetched during debug, is because when you are inspecting the grantedPermissions in debugger, it is accessing that property, which will trigger the lazy fetching. However, for non-debug mode, if you have no code accessing that property, no fetching is precisely what it supposed to do.
If what you are asking is, you have code in non-debug mode that will access grantedPermissions but lazy fetching failed when it is accessed, then it is due to the access is out of transaction: Hibernate needs to have an active Session to have lazy fetching happening. If the lazy-fetching happens out of the transaction, it will fail because there is no opened Session. You should revisit your design by considering
Scope of transaction: instead of having transaction around the DAO, you should put transaction boundary in a proper unit-of-work level: maybe your app service, or controller
Do proper join fetch/eager fetch, so that no lazy-fetching happens outside the transaction
EclipseLink, which is another JPA implementation, allows lazy-fetch after session is ended.
Follow http://docs.oracle.com/javaee/5/api/javax/persistence/FetchType.html
Example : If you want to auto load "grantedPermissions" in "Group", you have to change your annotation to #ManyToMany(fetch = FetchType.EAGER)

Spring Data JPA auditing feature is not working in my project

I am reading the book 'ProSpring3' and I am trying to use the Spring Data JPA feature in my project.
I am posting the relevant files here.
src/main/java/foo/bar/domain/ContactAudit.java :
package foo.bar.domain;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.springframework.data.domain.Auditable;
import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import static javax.persistence.GenerationType.IDENTITY;
#Table(name = "CONTACT_AUDIT")
#Entity
public class ContactAudit implements Auditable<String, Long>{
private Long id;
private String firstName;
private String lastName;
private Date birthDate;
private int version;
private Set<Hobby> hobbies = new HashSet<Hobby>();
private Set<ContactTelDetail> contactTelDetails = new HashSet<ContactTelDetail>();
//Audit fields
private String createdBy;
private DateTime createdDate;
private String lastModifiedBy;
private DateTime lastModifiedDate;
//constructors
public ContactAudit() {
}
public ContactAudit(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public ContactAudit(String firstName, String lastName, Date birthDate, Set<Hobby> hobbies, Set<ContactTelDetail> contactTelDetails) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
this.hobbies = hobbies;
this.contactTelDetails = contactTelDetails;
}
#Column(name = "ID")
#Id
#GeneratedValue(strategy = IDENTITY)
public Long getId() {
return id;
}
#Override
#Transient
public boolean isNew() {
if (id == null)
return true;
else
return false;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "BIRTH_DATE")
#Temporal(TemporalType.DATE)
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
#Column(name = "VERSION")
#Version
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
#ManyToMany
#JoinTable(name = "contact_hobby_detail",
joinColumns = #JoinColumn(name = "CONTACT_ID"),
inverseJoinColumns = #JoinColumn(name = "HOBBY_ID"))
public Set<Hobby> getHobbies() {
return hobbies;
}
public void setHobbies(Set<Hobby> hobbies) {
this.hobbies = hobbies;
}
#OneToMany(mappedBy = "contact", cascade = CascadeType.ALL, orphanRemoval = true)
public Set<ContactTelDetail> getContactTelDetails() {
return contactTelDetails;
}
public void setContactTelDetails(Set<ContactTelDetail> contactTelDetails) {
this.contactTelDetails = contactTelDetails;
}
#Column(name = "CREATED_BY")
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
#Column(name = "CREATED_DATE")
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
public DateTime getCreatedDate() {
return createdDate;
}
public void setCreatedDate(DateTime createdDate) {
this.createdDate = createdDate;
}
#Column(name = "LAST_MODIFIED_BY")
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
#Column(name = "LAST_MODIFIED_DATE")
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
public DateTime getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(DateTime lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
//other methods
public String toString()
{
return "Contact - Id: " + id + ", First name: " + firstName + ", Last name: " + lastName + ", Birthday: " + birthDate
+ ", Create by: " + createdBy + ", Create date: " + createdDate + ", Modified by: " + lastModifiedBy + ", Modifed date: " + lastModifiedDate;
}
}
src/main/java/foo/bar/repository/ContactAuditRepository.java :
package foo.bar.repository;
import foo.bar.domain.ContactAudit;
import org.springframework.data.repository.CrudRepository;
public interface ContactAuditRepository extends CrudRepository<ContactAudit, Long>{
}
src/main/java/foo/bar/service/ContactAuditService.java :
package foo.bar.service;
import foo.bar.domain.ContactAudit;
import java.util.List;
public interface ContactAuditService {
public List<ContactAudit> findAll();
public ContactAudit findById(Long id);
public ContactAudit save(ContactAudit contact);
}
src/main/java/foo/bar/service/springjpa/ContactAuditServiceImpl.java
package foo.bar.service.springjpa;
import com.google.common.collect.Lists;
import foo.bar.domain.ContactAudit;
import foo.bar.repository.ContactAuditRepository;
import foo.bar.service.ContactAuditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service("contactAuditService")
#Repository
#Transactional
public class ContactAuditServiceImpl implements ContactAuditService{
#Autowired
private ContactAuditRepository contactAuditRepository;
#Override
#Transactional(readOnly = true)
public List<ContactAudit> findAll() {
return Lists.newArrayList(contactAuditRepository.findAll());
}
#Override
#Transactional(readOnly = true)
public ContactAudit findById(Long id) {
return contactAuditRepository.findOne(id);
}
#Override
public ContactAudit save(ContactAudit contact) {
return contactAuditRepository.save(contact);
}
}
src/main/java/foo/bar/springjpa/auditor/AuditorAwareBean.java :
package foo.bar.springjpa.auditor;
import org.springframework.data.domain.AuditorAware;
public class AuditorAwareBean implements AuditorAware<String>{
#Override
public String getCurrentAuditor() {
return "prospring3";
}
}
src/main/resources/spring-config.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<context:annotation-config />
<context:component-scan base-package="foo.bar.service.springjpa"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>${jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="foo.bar.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.max_fetch_depth">3</prop>
<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<context:property-placeholder location="jdbc.properties"/>
<jpa:repositories base-package="foo.bar.repository"
entity-manager-factory-ref="emf"
transaction-manager-ref="transactionManager"/>
<jpa:auditing auditor-aware-ref="auditorAwareBean"/>
<bean id="auditorAwareBean" class="foo.bar.springjpa.auditor.AuditorAwareBean"/>
</beans>
src/main/java/META-INF/persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="NewPersistenceUnit"/>
</persistence>
src/main/java/META-INF/orm.xml :
<?xml version="1.0" encoding="UTF-8" ?>
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
version="2.0">
<description>JPA</description>
<persistence-unit-metadata>
<persistence-unit-defaults>
<entity-listeners>
<entity-listener class="org.springframework.data.jpa.domain.support.AuditingEntityListener"/>
</entity-listeners>
</persistence-unit-defaults>
</persistence-unit-metadata>
</entity-mappings>
--> And the starting point of the app
src/main/java/foo/bar/SpringJpaAuditSample.java :
package foo.bar;
import foo.bar.domain.ContactAudit;
import foo.bar.service.ContactAuditService;
import org.springframework.context.support.GenericXmlApplicationContext;
import java.util.Date;
import java.util.List;
public class SpringJpaAuditSample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("spring-config.xml");
ContactAuditService contactService = ctx.getBean("contactAuditService", ContactAuditService.class);
List<ContactAudit> contacts = contactService.findAll();
listContacts(contacts);
//Add new contact
System.out.println("Add new contact");
ContactAudit contact = new ContactAudit();
contact.setFirstName("Michael");
contact.setLastName("Jackson");
contact.setBirthDate(new Date());
contactService.save(contact);
contacts = contactService.findAll();
listContacts(contacts);
}
private static void listContacts(List<ContactAudit> contacts)
{
System.out.println("");
System.out.println("Listing contacts without details:");
for(ContactAudit contact: contacts)
{
System.out.println(contact);
System.out.println();
}
}
}
The findAll returns this :
Listing contacts without details:
Contact - Id: 4, First name: Michael, Last name: Jackson, Birthday: 2013-05-27, Create by: null, Create date: 2013-05-27T04:02:36.000+03:00, Modified by: null, Modifed date: 2013-05-27T04:02:36.000+03:00
Which means that I get null instead of the string 'prospring3'.
Any ideas?
Thank you.
The 'error' I had with this project created with IntelliJ Idea is that I let the IDE create the META-INF directory wherever it chose and I have not noticed that the author had placed it inside resources directory.
The motivation for this fix came out of this post ("No Persistence Unit Found" error).

Categories