#Vaild is not working - java

I want to check size validation for studentHobby object and i am using #Size annotation and Using #valid annotation.
I am providing less than the value defined in #Size annotation but still I am getting the result instead of error.
I tried things but didn't come with solutions.
StudentAdmissionController.java
package com.diwakar;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class StudentAdmissionController {
#InitBinder
public void initBinder(WebDataBinder binder) {
//binder.setDisallowedFields(new String[] {"studentMobile"});
//SimpleDateFormat date = new SimpleDateFormat("dd**MM**yyyy");
//binder.registerCustomEditor(Date.class, "studentDOB", new CustomDateEditor(date, false));
binder.registerCustomEditor(String.class, "studentName", new StudentNameEditor());
}
#RequestMapping(value="/admission.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
//model.addObject("headerMessage", "Diwakar College of Engineering.!!");
return model;
}
#RequestMapping(value="/submitForm", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#Valid #ModelAttribute("st1") Student st1, BindingResult result) {
if (result.hasErrors()) {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
ModelAndView model = new ModelAndView("AdmissionSuccess");
//model.addObject("headerMessage", "Diwakar College of Engineering.!!");
return model;
}
#ModelAttribute
public void addCommonMessage(Model model) {
model.addAttribute("headerMessage", "Diwakar College of Engineering.!!");
}
Student.java
package com.diwakar;
import java.util.ArrayList;
import java.util.Date;
import javax.validation.constraints.Size;
public class Student {
private String studentName;
#Size(min=3, max=10)
private String studentHobby;
private Long studentMobile;
private Date studentDOB;
private ArrayList<String> studentSkills;
private Address studentAddress;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentHobby() {
return studentHobby;
}
public void setStudentHobby(String studentHobby) {
this.studentHobby = studentHobby;
}
public Long getStudentMobile() {
return studentMobile;
}
public void setStudentMobile(Long studentMobile) {
this.studentMobile = studentMobile;
}
public Date getStudentDOB() {
return studentDOB;
}
public void setStudentDOB(Date studentDOB) {
this.studentDOB = studentDOB;
}
public ArrayList<String> getStudentSkills() {
return studentSkills;
}
public void setStudentSkills(ArrayList<String> studentSkills) {
this.studentSkills = studentSkills;
}
public Address getStudentAddress() {
return studentAddress;
}
public void setStudentAddress(Address studentAddress) {
this.studentAddress = studentAddress;
}
}
spring-dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean name="/welcome.html" class="com.diwakar.HelloController" /> -->
<context:component-scan base-package="com.diwakar" />
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
Here is my admission page even though i am providing one one character it is giving me submit form instead of error.
admission.html Page
This submit form i am getting after submitting value with 1 character.
submitForm

Related

UnsatisfiedDependencyException: Error creating bean with name "empController"

I want to learn Spring, so I write simple java CRUD app. But from the begining have errors org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController'" and org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dao' for my servlet. I was looking some solutions, but nothing works.
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Employer</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Employer</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Employer-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.javatpoint"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/Employers"></property>
<property name="username" value="root"></property>
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.javatpoint.EmpDao">
<property name="jdbcTemplate" ref="jt"></property>
</bean>
</beans>
EmpController.java
package com.javatpoint;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class EmpController {
#Autowired
EmpDao empDao;
#RequestMapping("/empform")
public ModelAndView show() {
return new ModelAndView("empform", "command", new Emp());
}
#RequestMapping(value="/save", method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp")Emp emp) {
empDao.save(emp);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping("/viewemp")
public ModelAndView viewemp() {
List<Emp> list = empDao.getEmployees();
return new ModelAndView("viewemp", "list", list);
}
#RequestMapping(value="/editemp/{id}")
public ModelAndView edit(#PathVariable("id")int id) {
Emp emp = empDao.getById(id);
return new ModelAndView("empeditform", "command", emp);
}
#RequestMapping(value="editsave", method=RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("emp")Emp emp) {
empDao.update(emp);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping("/delete")
public ModelAndView delete(#ModelAttribute("emp")Emp emp) {
empDao.delete(emp);
return new ModelAndView("redirect:/viewemp");
}
}
EmpDao.java
package com.javatpoint;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
public class EmpDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int save(Emp emp) {
String sql = "insert into Employers values('"+emp.getId()+"','"+emp.getName()+"','"+emp.getSalary()+"','"+emp.getDesignation()+"')";
return jdbcTemplate.update(sql);
}
public int update(Emp emp) {
String sql = "update Employers set name='"+emp.getName()+"',salary='"+emp.getSalary()+"',designation='"+emp.getDesignation()+"' where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public int delete(Emp emp) {
String sql = "delete from Employers where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public Emp getById(int id) {
String sql = "select * form Employers where id=?";
return jdbcTemplate.queryForObject(sql, new Object[] {id}, new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return jdbcTemplate.query("select * from Employers", new RowMapper<Emp>() {
public Emp mapRow(ResultSet rs, int row) throws SQLException{
Emp emp = new Emp();
emp.setId(rs.getInt(1));
emp.setName(rs.getString(2));
emp.setSalary(rs.getFloat(3));
emp.setDesignation(rs.getString(4));
return emp;
}
});
}
}
Emp.java
package com.javatpoint;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
The main problem is that you're trying to autowire an EmpDao to your controller without havin an EmpDao bean.
In order to make EmpDao a bean you should annotate the EmpDao class with #Component , #Service or #Repository:
#Service
public class EmpDao {
#Autowired
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int save(Emp emp) {
String sql = "insert into Employers values('"+emp.getId()+"','"+emp.getName()+"','"+emp.getSalary()+"','"+emp.getDesignation()+"')";
return jdbcTemplate.update(sql);
}
public int update(Emp emp) {
String sql = "update Employers set name='"+emp.getName()+"',salary='"+emp.getSalary()+"',designation='"+emp.getDesignation()+"' where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public int delete(Emp emp) {
String sql = "delete from Employers where id='"+emp.getId()+"'";
return jdbcTemplate.update(sql);
}
public Emp getById(int id) {
String sql = "select * form Employers where id=?";
return jdbcTemplate.queryForObject(sql, new Object[] {id}, new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return jdbcTemplate.query("select * from Employers", new RowMapper<Emp>() {
public Emp mapRow(ResultSet rs, int row) throws SQLException{
Emp emp = new Emp();
emp.setId(rs.getInt(1));
emp.setName(rs.getString(2));
emp.setSalary(rs.getFloat(3));
emp.setDesignation(rs.getString(4));
return emp;
}
});
}
}
Remember, you can only inject (or autowire) other beans into your beans.
In spring, the application creates it's own beans (either as singletons, or a 'new' instance anytime you need it.)
EmpController for example is annotated with #Controller to tell spring exactly that- this is a controller, as the application starts up, please create a new instance of this bean, so I can use it.
However, as spring tries to create this bean, it also populates it's variables.
#Autowired on the empDao variable means roughly: "you should already have built an instance of the class empDao, so please, let me have here a reference to it(empDao) so I can call it from this class(empController)"
#Controller
public class EmpController {
#Autowired
EmpDao empDao;
But it seems empDao itself is not configured properly- no annotation to let spring know it should create an instance of it while starting up.
try the following 2 changes:
#Service
public class EmpDao {
and
#Entity
public class Emp {

Getting error "Injection of autowired dependencies failed;" when adding another entity class to annotedClasses list in spring

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 {

Spring + TestNG not transactionally rollback

I'm using TestNG 6.9.9 to build-up a regression test environment. But encounter a problem which I have never met when using JUnit.
In my mind, when finish each test cases, the change of each data would be automatically rollback by default if the test methods run in the same transaction context as what they call. But seems that it's not the truth, and I cannot find out if any mistake in my code. Please help me out.
properties in pom.xml which indicates the frameworks' version
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springframework.version>4.2.4.RELEASE</springframework.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<testng.version>6.9.9</testng.version>
</properties>
Obviously, they are all up-to-date.
My test class:
package com.noahwm.hkapp.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.noahwm.hkapp.api.db.dao.AppUserDao;
import com.noahwm.hkapp.api.db.model.AppUser;
import com.noahwm.hkapp.api.service.AppUserService;
#ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
public class AppUserServiceTestNGTest extends AbstractTestNGSpringContextTests {
#Autowired
private AppUserService appUserService;
#Test
#Rollback
#Transactional
public void testApp() {
AppUser appUser = new AppUser();
appUser.setAge(10);
appUser.setGender("F");
appUser.setMobilePhone("13219201034");
appUser.setName("HKAPP Test");
appUserService.createUser(appUser);
String appUserId = appUser.getId();
Assert.assertNotNull(appUserId);
}
}
Created a entity instance, than call createUser() to save it to DB. According what I have done in JUnit, the data will automatically rollback even if I didn't put the #Rollback annotation in the front of the test method.
The structure of AppUser is:
package com.noahwm.hkapp.api.db.model;
import javax.persistence.Column;
import javax.persistence.Entity;
#Entity(name = "APP_USERS")
public class AppUser extends BaseDataModel {
#Column(name = "NAME")
private String name;
#Column(name = "GENDER")
private String gender;
#Column(name = "AGE")
private Integer age;
#Column(name = "MOBILE_PHONE")
private String mobilePhone;
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
}
BaseDataModel.java
package com.noahwm.hkapp.api.db.model;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import org.hibernate.annotations.GenericGenerator;
#MappedSuperclass
public class BaseDataModel {
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
#Column(name = "ID", unique = true, length = 36, nullable = false)
protected String id;
#Version
#Column(name = "version")
protected Integer version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
}
ApplicationContext-test.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-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/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.test.properties</value>
</property>
</bean>
<context:annotation-config />
<context:component-scan base-package="com.noahwm.hkapp.api" />
<aop:aspectj-autoproxy />
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler"
lazy-init="true" />
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxConnectionsPerPartition" value="${jdbc.maxConnectionsPerPartition}" />
<property name="minConnectionsPerPartition" value="${jdbc.minConnectionsPerPartition}" />
<property name="partitionCount" value="${jdbc.partitionCount}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.noahwm.hkapp.api.db.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.jdbc.batch_size">10</prop>
<prop key="hibernate.jdbc.fetch_size">30</prop>
<prop key="hibernate.default_batch_fetch_size">10</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager"
proxy-target-class="true" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
The transaction-manager is named “txManager”.
AppUserService.java
package com.noahwm.hkapp.api.service;
import java.util.List;
import java.util.Map;
import com.noahwm.hkapp.api.db.dao.AppUserDao;
import com.noahwm.hkapp.api.db.model.AppUser;
public interface AppUserService {
void createUser(AppUser user);
}
AppUserServiceImpl.java
package com.noahwm.hkapp.api.service.impl;
import java.util.List;
import java.util.Map;
import org.hibernate.criterion.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.noahwm.hkapp.api.db.dao.AppUserDao;
import com.noahwm.hkapp.api.db.model.AppUser;
import com.noahwm.hkapp.api.service.AppUserService;
import com.noahwm.hkapp.api.service.EntityService;
import com.noahwm.hkapp.utils.SimpleSearchCriteria;
#Service("AppUserService")
#Transactional(propagation=Propagation.REQUIRED)
public class AppUserServiceImpl extends EntityService implements AppUserService {
private static final Logger logger = LoggerFactory.getLogger(AppUserServiceImpl.class);
#Autowired
private AppUserDao dao;
#Override
public void createUser(AppUser user) {
logger.debug("Creating user with name {}", user.getName());
dao.save(user);
}
}
AppUserDao.java
package com.noahwm.hkapp.api.db.dao;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.noahwm.hkapp.api.db.model.AppUser;
#Repository
#Transactional(propagation=Propagation.REQUIRED)
public class AppUserDao extends BaseDao<AppUser> {
public void testsRollBack(AppUser appUser) throws Exception{
save(appUser);
}
}
BaseDao.java
package com.noahwm.hkapp.api.db.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Resource;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import com.noahwm.hkapp.api.db.model.BaseDataModel;
import com.noahwm.hkapp.utils.SimpleSearchCriteria;
class BaseDao<T extends BaseDataModel> {
private Class<T> domainClass;
#Resource(name = "sessionFactory")
protected SessionFactory sessionFactory;
protected SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#SuppressWarnings("unchecked")
public Class<T> getDomainClass() {
if (domainClass == null) {
Type type = this.getClass().getGenericSuperclass();
ParameterizedType parameterizedType = (ParameterizedType) type;
domainClass = (Class<T>) parameterizedType.getActualTypeArguments()[0];
}
return domainClass;
}
protected Session getCurrentSession() {
return getSessionFactory().getCurrentSession();
}
public Criteria createCriteria() {
return getCurrentSession().createCriteria(getDomainClass());
}
public void save(T o) {
getCurrentSession().save(o);
}
public void update(T o) {
getCurrentSession().update(o);
}
public void saveOrUpdate(T o) {
getCurrentSession().saveOrUpdate(o);
}
public Object merge(Object o) {
return getCurrentSession().merge(o);
}
public void delete(T o) {
getCurrentSession().delete(o);
}
public T deleteById(Serializable id) {
T o = findById(id);
getCurrentSession().delete(o);
return o;
}
public void evict(Object o) {
getCurrentSession().evict(o);
}
#SuppressWarnings("unchecked")
public List<T> findAll() {
return createCriteria().list();
}
#SuppressWarnings("unchecked")
public T findById(Serializable o) {
List<T> results = createCriteria().add(Restrictions.idEq(o)).list();
if (results.isEmpty()) {
return null;
} else {
return results.get(0);
}
}
#SuppressWarnings("unchecked")
public T load(Serializable o) {
return (T) getCurrentSession().load(getDomainClass(), o);
}
#SuppressWarnings("unchecked")
public List<T> findBy(Map<String, Object> propertyNameValues) {
return createCriteria().add(Restrictions.allEq(propertyNameValues)).list();
}
#SuppressWarnings("unchecked")
public List<T> findBy(String propertyName, Object value) {
return createCriteria().add(Restrictions.eq(propertyName, value)).list();
}
#SuppressWarnings("unchecked")
public List<T> find(SimpleSearchCriteria simpleSearchCriteria) {
Criteria criteria = createCriteria();
Iterator<Criterion> criterions = simpleSearchCriteria.iterator();
while(criterions.hasNext()) {
criteria.add(criterions.next());
}
for(Order o : simpleSearchCriteria.getOrders()) {
criteria.addOrder(o);
}
if(simpleSearchCriteria.getFetchSize() != null) {
criteria.setFetchSize(simpleSearchCriteria.getFetchSize());
}
if(simpleSearchCriteria.getFirstResult() != null) {
criteria.setFirstResult(simpleSearchCriteria.getFirstResult());
}
if(simpleSearchCriteria.getMaxResults() != null) {
criteria.setMaxResults(simpleSearchCriteria.getMaxResults());
}
if(simpleSearchCriteria.getTimeout() != null) {
criteria.setTimeout(simpleSearchCriteria.getTimeout());
}
return criteria.list();
}
public T findFirst(SimpleSearchCriteria simpleSearchCriteria) {
simpleSearchCriteria.setMaxResults(1);
List<T> results = find(simpleSearchCriteria);
if(results.isEmpty()) {
return null;
} else {
return results.get(0);
}
}
public Object callNamedQuery(String sql, Map<String, Object> parameter) {
Query query = getCurrentSession().createSQLQuery(sql);
for(Entry<String, Object> entry:parameter.entrySet()){
query.setParameter(entry.getKey(), entry.getValue());
}
return query.executeUpdate();
}
}
Here is the DB init script:
CREATE TABLE "APP_USERS" (
"ID" VARCHAR(36),
"NAME" VARCHAR(50),
"GENDER" VARCHAR(1),
"AGE" NUMERIC(3,0),
"MOBILE_PHONE" VARCHAR(20),
VERSION INTEGER)
As you see, it's a very common Spring TestNG integration test. But the auto rollback function cannot be used which bordered me a lot.
Thanks to M. Deinum.
To solve my problem, I just replace the class AbstractTestNGSpringContextTests with AbstractTransactionalTestNGSpringContextTests.
package com.noahwm.hkapp.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.noahwm.hkapp.api.db.dao.AppUserDao;
import com.noahwm.hkapp.api.db.model.AppUser;
import com.noahwm.hkapp.api.service.AppUserService;
#ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
public class AppUserServiceTestNGTest extends AbstractTransactionalTestNGSpringContextTests {
#Autowired
private AppUserService appUserService;
#Test
#Rollback
#Transactional
public void testApp() {
AppUser appUser = new AppUser();
appUser.setAge(10);
appUser.setGender("F");
appUser.setMobilePhone("13219201034");
appUser.setName("HKAPP Test");
appUserService.createUser(appUser);
String appUserId = appUser.getId();
Assert.assertNotNull(appUserId);
}
}

Spring + Oracle doesn't persists

I have a problem with Spring and Oracle, I can select objects, but I can't update and insert. (I usually use MySql)
Aplication context:
<?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"
xmlns:c="http://www.springframework.org/schema/c"
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.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- enabling annotation driven configuration /-->
<context:annotation-config/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="{jdbc.username}"
p:password="${jdbc.password}" />
<bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate"
c:dataSource-ref="dataSource" />
<bean id="jdbcTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/>
<tx:annotation-driven transaction-manager="jdbcTransactionManager"/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceUnitName" value="namePU"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="package.repository" />
<context:component-scan base-package="package.service" />
</beans>
jdbc.properties:
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:#172.172.10.83:1521:orcl
jdbc.username=User
jdbc.password=Password
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
jpa.database = ORACLE
hibernate.generate_statistics = true
hibernate.show_sql = true
jpa.showSql = true
jpa.generateDdl = true
Usuario class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "USUARIO")
public class Usuario implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ID_USUARIO")
private String idUsuario;
#Column(name = "LOGIN")
private String login;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_AMBITO")
private Ambito ambito;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "ID_ROL")
private Rol rol;
public String getIdUsuario() {
return idUsuario;
}
public void setIdUsuario(String idUsuario) {
this.idUsuario = idUsuario;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Ambito getAmbito() {
return ambito;
}
public void setAmbito(Ambito ambito) {
this.ambito = ambito;
}
public Rol getRol() {
return rol;
}
public void setRol(Rol rol) {
this.rol = rol;
}
}
JPAUsuarioDao
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository(value = "usuarioDao")
public class JPAUsuarioDao implements UsuarioDao {
private EntityManager em = null;
#PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
#Override
#Transactional(readOnly = true)
public List<Usuario> getUsuariosList() {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u",
Usuario.class);
return query.getResultList();
}
#Override
#Transactional(readOnly = true)
public Usuario getUsuario(String login) throws NoResultException {
TypedQuery<Usuario> query = em.createQuery("SELECT u FROM Usuario u WHERE u.login ='" + login + "'",
Usuario.class);
return query.getSingleResult() ;
}
#Override
#Transactional(readOnly = false)
public void addUsuario(Usuario usuario) {
em.merge(usuario);
}
}
This is the exception afer em.merge:
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No unresolved entity inserts that depended on [[package.domain.Usuario#70675c9a-5eb4-4241-aa83-9cdea9211d18]]
TRACE: org.hibernate.action.internal.UnresolvedEntityInsertActions - No entity insert actions have non-nullable, transient entity dependencies.
Thank you

org.hibernate.MappingException: Could not determine typ

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 /.

Categories