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).
Related
While Executing the program, I'm getting the particular error
**Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException:
Write operations are not allowed in read-only mode (FlushMode.MANUAL):
Turn your Session into FlushMode.
COMMIT/AUTO or remove 'readOnly' marker from transaction definition.**
every time. please someone help me. Here I am giving my codes which contains some error. In the Below code I have taken one employee data which will be stored in the employee table of MSSQL database. While working with only hibernate at that time i can able to persist my data. But, her i am unable to persist my data.
EmployeeHt.java
This is the entity class which is mapped to the employee table of MSSQL database
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class EmployeeHt {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Column(name="salary")
private int salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString() {
return "EmployeeHt [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
}
EmployeeHtDao.java
This is the class which contains hibernate template
import org.springframework.orm.hibernate5.HibernateTemplate;
public class EmployeeHtDao {
private HibernateTemplate ht;
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
public void saveEmployee(EmployeeHt e){
ht.save(e);
}
}
EmployeeHtTest.java
**This is the main class**
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class EmployeeHtTest {
private static ApplicationContext context;
public static void main(String[] args) {
context = new ClassPathXmlApplicationContext("hibernateTemplate.xml");
EmployeeHtDao dao=(EmployeeHtDao) context.getBean("edao");
EmployeeHt e=new EmployeeHt();
e.setId(104);
e.setName("Prangyan");
e.setSalary(30000);
dao.saveEmployee(e);
}
}
hibernateTemplate.xml
**This is the spring-xml file**
<?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-3.0.xsd">
<bean id="connpool" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=ananta"/>
<property name="username" value="sa"/>
<property name="password" value="pass123"/>
</bean>
<bean id="mysessionfactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="connpool"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionfactory"/>
</bean>
<bean id="edao" class="com.sdrc.hibernatetemplate.EmployeeHtDao">
<property name="ht" ref="hibernateTemplate"/>
</bean>
</beans>
Check for #Transactional annotation in you DAO.
It should be
#Transactional(readOnly = false)
Please help me I am totally stuck at one thing.
In my program everything was running fine when I was working with only one entity class called Person but when i have added one more entity class called Specimen it throws me exception like "hibernate exception unknown entity Specimen" after searching on google I have added "Specimen" class in annottedClasses list but after adding it throwing me exception
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'homeController': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private com.swapnil.service.RegisterService
Below is my code:
Home controller:
package com.swapnil.controller;
import javax.validation.Valid;
import org.omg.CORBA.portable.ApplicationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.swapnil.models.Person;
import com.swapnil.models.User;
import com.swapnil.service.RegisterService;
#Controller
public class HomeController {
#Autowired
private RegisterService registerService;
#RequestMapping(value = "/", method = { RequestMethod.GET,
RequestMethod.POST })
public String welcomePage(ModelMap map) {
System.out.println("*****");
map.addAttribute("message", "Welcome to Spring mvc");
return "welcome";
}
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String displayregistrationPage(Model map) {
User userObj = new User();
map.addAttribute("user", userObj);
return "register";
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String doRegistration(#Valid #ModelAttribute("user") User user,
BindingResult result, Model model) {
int id = 0;
System.out.println(user);
if (result.hasErrors()) {
return "register";
} else {
if (!registerService.checkUser(user)) {
try {
id = registerService.addUser(user);
} catch (ApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
model.addAttribute("userid", id);
return "login";
}
#RequestMapping(value = "/shortregister", method = { RequestMethod.GET })
public String shortregister(Model map) {
Person personObj = new Person();
map.addAttribute("person", personObj);
return "shortReg";
}
#RequestMapping(value = "/shortregister", method = { RequestMethod.POST })
public String shortregisterDo(Model map,
#Valid #ModelAttribute("person") Person person, BindingResult result) {
if (result.hasErrors()) {
// throw new CustomGenericException("407",
// "something is missing required for registration");
return "shortReg";
} else {
registerService.addPerson(person);
return "welcome";
}
}
}
personDAO:-
package com.swapnil.dao;
import java.util.List;
import com.swapnil.models.Person;
import com.swapnil.models.Specimen;
public interface PersonDAO {
public void save(Person p);
public List<Person> list();
public int addSpecimen(Specimen specimen);
}
personDAOImpl--
package com.swapnil.dao;
import java.util.List;
import javax.sql.DataSource;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.swapnil.models.Person;
import com.swapnil.models.Specimen;
#Repository
public class PersonDAOImpl implements PersonDAO {
protected SessionFactory sessionFactory;
protected DataSource ds;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public DataSource getDs() {
return ds;
}
public void setDs(DataSource ds) {
this.ds = ds;
}
#Override
#Transactional
public void save(Person p) {
// TODO Auto-generated method stub
System.out.println("session factipwpf " + sessionFactory);
Session session = sessionFactory.openSession();
System.out.println("sesstion " + session);
// System.out.println("connection "+session.connection());
Transaction tx = session.beginTransaction();
System.out.println(p);
// System.out.println("last saved user "+session.save(p));
// session.persist(p);
// System.out.println("persist id "+session.getIdentifier(p));
SQLQuery query = session
.createSQLQuery("insert into person(id,name,country) values(:id,:name,:country)");
query.setParameter("id", p.getId());
query.setParameter("name", p.getName());
query.setParameter("country", p.getCountry());
query.executeUpdate();
tx.commit();
session.close();
}
#Override
public List<Person> list() {
// TODO Auto-generated method stub
Session session = sessionFactory.openSession();
Query query = session.createQuery("from person");
List<Person> plist = query.list();
return plist;
}
#Override
#Transactional
public int addSpecimen(Specimen specimen) {
// TODO Auto-generated method stub
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
int id = (Integer) session.save(specimen);
tx.commit();
return id;
}
}
RegisterService--
package com.swapnil.service;
import com.swapnil.models.Person;
import com.swapnil.models.Specimen;
import com.swapnil.models.User;
public interface RegisterService {
public Boolean checkUser(User user);
public int addUser(User user);
public int addPerson(Person person);
public int addspecimen(Specimen specimen);
}
RegisterServiceImpl--
package com.swapnil.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.swapnil.dao.PersonDAO;
import com.swapnil.models.Person;
import com.swapnil.models.Specimen;
import com.swapnil.models.User;
#Service
public class RegisterServiceImpl implements RegisterService {
#Autowired
PersonDAO personDAO;
#Override
public Boolean checkUser(User user) {
boolean userPresentFlag = false;
if (null != user) {
if (user.getFname().equalsIgnoreCase("swapnil")) {
userPresentFlag = true;
}
}
return userPresentFlag;
}
#Override
public int addUser(User user) {
int id;
if (null == user) {
throw new NullPointerException();
} else {
id = user.getUserid();
}
return id;
}
#Override
public int addPerson(Person person) {
personDAO.save(person);
return 0;
}
#Override
public int addspecimen(Specimen specimen) {
return personDAO.addSpecimen(specimen);
}
}
below is the my configuration file-
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.swapnil.controller"/>
<context:component-scan base-package="com.swapnil.service"/>
<context:component-scan base-package="com.swapnil.dao"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"/>
<property name="username" value="swapnil" />
<property name="password" value="swapnil" />
</bean>
<bean id="hibernate3AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.swapnil.models.Person</value>
<value>com.swapnil.models.Specimen</value>
</list>
</property>
<!-- <property name="packagesToScan" value="com.swapnil.models" ></property> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.default_schema">SWAPNIL</prop>
</props>
</property>
</bean>
<bean id="personDAO" class="com.swapnil.dao.PersonDAOImpl">
<property name="sessionFactory" ref="hibernate3AnnotatedSessionFactory" />
</bean>
</beans>
every thing was fine before adding com.swapnil.models.Specimen in configuration file please help me.
below is the snap of Specimen class
Specimen---
package com.swapnil.models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name = "SPECIMEN_DETAILS")
public class Specimen {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SPECIMEN_DETAILS_SEQ")
private int id;
#Size(min = 4, max = 8)
#Column(name = "username")
private String username;
#NotNull
#Min(value = 1)
private int specimenid;
#NotNull
#Min(value = 1)
private int projectid;
#NotNull
#Min(value = 1)
private int technologyid;
#Size(min = 4)
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getSpecimenid() {
return specimenid;
}
public void setSpecimenid(int specimenid) {
this.specimenid = specimenid;
}
public int getProjectid() {
return projectid;
}
public void setProjectid(int projectid) {
this.projectid = projectid;
}
public int getTechnologyid() {
return technologyid;
}
public void setTechnologyid(int technologyid) {
this.technologyid = technologyid;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Specimen [id=" + id + ", username=" + username
+ ", specimenid=" + specimenid + ", projectid=" + projectid
+ ", technologyid=" + technologyid + ", description="
+ description + "]";
}
}
Try to write the #Service like this:
#Service("registerService")
public class RegisterServiceImpl implements RegisterService {
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;
}
}
I'm getting this error while trying to get a bean from spring context on standalone java application. I'm using jdk 1.6.0_37 and hibernate-jpa-2.0-api-1.0.0.Final.jar
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mesarimLogService' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:527)
the log-config.xml is :
<?xml version="1.0" encoding="UTF-8"?>
<!-- Repository and Service layers -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:property-placeholder
location="classpath:calypsox/infra/hib/resources/database.properties"
system-properties-mode="OVERRIDE"/>
<!-- DataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"
p:username="${jdbc.username}" p:password="${jdbc.password}"/>
<jdbc:initialize-database data-source="dataSource"
enabled="${jdbc.init}" ignore-failures="ALL">
<jdbc:script location="${jdbc.initLocation}"/>
</jdbc:initialize-database>
<!-- === Hibernate Session Factory === -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>calypsox.infra.hib.model.MesarimDBLogRecord</value>
</list>
</property>
</bean>
<context:component-scan base-package="calypsox.infra.hib.service"/>
</beans>
and the code is:
MesarimLogDaoImpl.java
package calypsox.infra.hib.service;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import com.calypso.engine.risk.Log;
import calypsox.infra.hib.model.MesarimDBLogRecord;
#Repository("logDao")
public class MesarimLogDaoImpl extends HibernateDaoSupport implements MesarimLogDao {
#Override
public void save(MesarimDBLogRecord msg) {
try {
//must handle exceptions internally!
getHibernateTemplate().save(msg);
} catch (Exception e) {
Log.error(Log.ERROR, "CANT LOG!!!! Failed to write DB log:", e);
}
}
#Autowired
public void anyMethodName(SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}
}
MesarimLogServiceImpl.java
package calypsox.infra.hib.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import calypsox.infra.hib.model.MesarimDBLogRecord;
#Service("mesarimLogService")
public class MesarimLogServiceImpl implements MesarimLogService {
#Autowired
MesarimLogDao logDao;
#Override
public void log(MesarimDBLogRecord msg) {
logDao.save(msg);
}
#Override
public void error(MesarimDBLogRecord msg) {
if (msg.getError() == null) msg.setError("Unexpected error!");
log(msg);
}
}
package calypsox.infra.hib.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
#MappedSuperclass
public abstract class BaseLogRecord implements Serializable {
public BaseLogRecord() {
setTimestamp(new Date());
}
#Column(name = "TIME_STAMP")
private Date timestamp;
#Column(name = "ERROR")
private String error;
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
package calypsox.infra.hib.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import ext.mesarim.out.MesarimXmlData;
import ext.mesarim.out.MesarimXmlFormatter;
/**
* POJO object - represent log record that will be stored to DB table using hibernate.
* Contain message id, meta data, error and final xml (without pdf content)
*
*/
#Entity
#Table(name = "MESARIM_LOG")
public class MesarimDBLogRecord extends BaseLogRecord {
#Id
#Column(name = "MESSAGE_ID")
private int messageId;
//Meta:
//BRANCH_NUMBER_CUSTOM
#Column(name = "BRANCH_NUMBER_CUSTOM")
private String branchNumber;
//ACCOUNT_NUMBER_CUSTOM
#Column(name = "ACCOUNT_NUMBER_CUSTOM")
private String accountNumber;
//ACCOUNT_TYPE_CUSTOM
#Column(name = "ACCOUNT_TYPE_CUSTOM")
private String accountType;
//LE_Cust_Type
#Column(name = "LE_CUST_TYPE")
private String custType;
//LE_CUSTOMER_INDEX
#Column(name = "LE_CUSTOMER_INDEX")
private String custIndex;
//LE_ROTEM_NUMBER
#Column(name = "LE_ROTEM_NUMBER")
private String rotemIndex;
//SENDER_FULL_NAME
#Column(name = "SENDER_FULL_NAME")
private String senderName;
//BROKER_FULL_NAME
#Column(name = "BROKER_FULL_NAME")
private String brokerName;
//fax
#Column(name = "FAX")
private String fax;
#Column(name = "XML")
private String xmlStr;
public MesarimDBLogRecord(int msgId) {
super();
setMessageId(msgId);
setError("Mesarim Gateway: start parsing meta data.");
}
public int getMessageId() {
return messageId;
}
public void setMessageId(int messageId) {
this.messageId = messageId;
}
public String getBranchNumber() {
return branchNumber;
}
public void setBranchNumber(String branchNumber) {
this.branchNumber = branchNumber;
}
public String getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(String accountNumber) {
this.accountNumber = accountNumber;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public String getCustType() {
return custType;
}
public void setCustType(String custType) {
this.custType = custType;
}
public String getCustIndex() {
return custIndex;
}
public void setCustIndex(String custIndex) {
this.custIndex = custIndex;
}
public String getRotemIndex() {
return rotemIndex;
}
public void setRotemIndex(String rotemIndex) {
this.rotemIndex = rotemIndex;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getBrokerName() {
return brokerName;
}
public void setBrokerName(String brokerName) {
this.brokerName = brokerName;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getXmlStr() {
return xmlStr;
}
public void setXmlStr(String xmlStr) {
this.xmlStr = xmlStr;
}
public MesarimDBLogRecord updateMetaData(MesarimXmlData xmlData) {
if(xmlData == null) {
setError("Xml data is null - failed to parse meta data.");
}
else {
setBranchNumber(xmlData.getBranchNumber());
setAccountNumber(xmlData.getAccountNumber());
setAccountType(xmlData.getAccountType());
setCustType(xmlData.getCustType());
setCustIndex(xmlData.getCustomersIndex());
setRotemIndex(xmlData.getRotem());
setSenderName(xmlData.getSenderFullName());
setBrokerName(xmlData.getBroker());
setFax(xmlData.getFaxesAsString());
setError("Meta data was successfully parsed.");
}
return this;
}
public MesarimDBLogRecord setXmlWithoutPdfsContent(StringBuffer xml) {
setXmlStr(MesarimXmlFormatter.removePdfContent(xml));
setError("Mesarim xml was successfully created and sent.");
return this;
}
public MesarimDBLogRecord setFailed(String e) {
setError("ERROR! " + e);
return this;
}
}
the client part :
public class GatewayMesarimDocumentSender extends GatewayCAMELDocumentSender {
public static Properties props;
public static MesarimLogService dbLogger;
static {
try {
// get properties on static phase
props = GatewayUtil.readPropertyFile("BLLresources/gateway/mesarim_config.properties");
// init spring application context for logger
ApplicationContext appCtx = new ClassPathXmlApplicationContext("calypsox/infra/hib/resources/log-config.xml");
// get db logger
dbLogger = (MesarimLogService) appCtx.getBean(MesarimLogService.class);
Log.debug(Log.CALYPSOX, "GatewayMesarimDocumentSender:dbLogger" + dbLogger);
if (dbLogger == null)
Log.error(Log.ERROR, "Failed to retrieve db logger reference.");
} catch (IOException e) {
Log.error(Log.ERROR, "Unexpected error reading property file:", e);
}
}
private StringBuffer outputXml;
public static boolean isTest = Boolean.valueOf(props.getProperty("TEST_MODE.IS_TESTING"));
public GatewayMesarimDocumentSender() {
super();
Log.info(this, "Starting " + getClass().getName());
}
Can you help ? thank you
It should be this to look up beans by their name :
dbLogger = (MesarimLogService) appCtx.getBean("mesarimLogService");
well in fact you should not use getBean, as it is service locator pattern, not inversion of control.
I'm getting this error.
org.hibernate.MappingException: Could not determine type for: dom.Whore, at table: Message, for columns: [org.hibernate.mapping.Column(receiver)]
This is the class that is being mapped into the table.
package dom;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.stereotype.Component;
#Component
#Entity
public class Message {
private Whore sender;
private Whore receiver;
private Date date = new Date();
private String messageText;
private Boolean read;
private long id;
public Message(){}
public Message(Whore sender, Whore receiver) {
this.sender = sender;
this.receiver = receiver;
}
public Whore getSender() {
return sender;
}
public void setSender(Whore sender) {
this.sender = sender;
}
public Whore getReceiver() {
return receiver;
}
public void setReceiver(Whore receiver) {
this.receiver = receiver;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public Boolean getRead() {
return read;
}
public void setRead(Boolean read) {
this.read = read;
}
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy="increment")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
This is the class that the type can't be determined for.
package dom;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.stereotype.Component;
#Component
#Entity
public class Whore {
private String username;
private String password;
private String email;
private List<Whore> friends = new ArrayList<Whore>();
private int reputation;
private long id;
private List<Message> messages = new ArrayList<Message>();
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getReputation() {
return reputation;
}
public void setReputation(int reputation) {
System.out.println("in set reputation : " + reputation);
this.reputation = this.reputation + reputation;
System.out.println("new repuration : " + this.reputation);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Id
#GeneratedValue(generator="increment")
#GenericGenerator(name="increment", strategy="increment")
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;
}
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Whore> getFriends() {
return friends;
}
public void setFriends(List<Whore> friends) {
this.friends = friends;
}
public void addFriend(Whore friend) {
getFriends().add(friend);
}
public void removeFriend(Whore friend) {
getFriends().remove(friend);
}
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public void addMessage(Message message) {
getMessages().add(message);
}
}
I've read in a lot of posts that it's to do with not setting annotations on fields and getters at the same time. But as you can see that's not the cause here. I'm stumped.
<?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="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<context:component-scan base-package="/dom" />
<context:component-scan base-package="/dao" />
<context:component-scan base-package="/controllers" />
<context:component-scan base-package="/services" />
<context:component-scan base-package="/security" />
<tx:annotation-driven />
<mvc:annotation-driven />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/culturewhore" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="/" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="mappingJacksonHttpMessageConverter" />
</util:list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:maxUploadSize="1000000" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
Also I've just tried using #ManyToOne on the sender and receiver getters. But this didn't make any difference.
You haven't mapped the message to whore relationship inside message. Should be:
#ManyToOne
public Whore getSender() {
return sender;
}
#ManyToOne
public Whore getReceiver() {
return receiver;
}
Comment : You shouldn't annotate / use your entity as #Component
You should remove the leading slash ("/") character from your <context:component-scan> tags, and the packagesToScan property of your sessionFactory should be *, not /.