I am getting the error "Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)" while executing my spring program. I am new to Spring core and trying to learn the framework. Below is the code:
Student.java
package com.inject.test;
public class Student {
private String name;
private String className;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
Address.java
package com.inject.test;
public class Address {
private String city;
private String state;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Test.java
package com.inject.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
#SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("file:com/applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println("Name: " + student.getName());
System.out.println("Class: " + student.getClassName());
Address studentAddress = student.getAddress();
System.out.println("Student Address: ");
System.out.println("City: " + studentAddress.getCity());
System.out.println("State: " + studentAddress.getState());
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="student" class="com.inject.test.Student">
<property name="name" value="Jai"/>
<property name="className" value="MCA"/>
<constructor-arg ref="address" type="java.lang.String"/>
</bean>
<bean id="address" class="com.inject.test.Address">
<property name="city" value="Hyderabad"/>
<property name="state" value="Telangana"/>
</bean>
</beans>
What change should be made to resolve the constructor issue, please suggest.
Your xml configuration specifies a constructor argument containing the address, but your Student class does not have a constructor that takes any arguments.
Either add the appropriate constructor, or change the constructor-arg to a property in the xml configuration.
1)you have not added constructor in your class,so replace your applicationContext.xml file
<bean id="student" class="com.inject.test.Student">
<property name="name" value="jai"></property>
<property name="className" value="MCA"></property>
//instead of writing <constructor-arg>property write as follow
<property name="address" ref="addressOne"></property>
</bean>
<bean id="addressOne" class="com.inject.test.Address">
<property name="city" value="Hyderabad"/>
<property name="state" value="Telangana"/>
</bean>
or 2) just add
public Student(Address address) {
this.address = address;
}
in student class
and replace this line
<constructor-arg ref="address" type="java.lang.String"/>
with this
<constructor-arg ref="address"/>
Related
I have created a package com.springcore.autowire.Annotations which contains 4 files Emp.java, Address.java, awannconfig.xml, Test.java .
Emp.java contains class Emp with code as -
package com.springcore.autowire.Annotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class Emp {
private Address address;
public Address getAddress() {
return this.address;
}
#Autowired
#Qualifier("address")
public void setAddress(Address address) {
this.address = address;
}
public Emp(Address address) {
this.address = address;
}
#Override
public String toString() {
return "{" + " address='" + getAddress() + "'" + "}";
}
}
Address.java contains class Address with code-
package com.springcore.autowire.Annotations;
public class Address {
private String street;
private String city;
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public Address(String street, String city) {
this.street = street;
this.city = city;
}
#Override
public String toString() {
return "{" + " street='" + getStreet() + "'" + ", city='" + getCity() + "'" + "}";
}
}
awannconfig.xml file -
<?xml version="1.0" encoding="UTF-8"?>
<!-- We get this template from documentation -->
<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" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean class="com.springcore.autowire.Annotations.Emp" name="emp" />
<bean class="com.springcore.autowire.Annotations.Address" name="address">
<property name="street" value="PA-24" />
<property name="city" value="Muradnagar" />
</bean>
<!-- more bean definitions go here -->
</beans>
Test.java contains Test class with main method to check use of #Autowired annotations .
package com.springcore.autowire.Annotations;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.ApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/springcore/autowire/Annotations/awannconfig.xml");
Emp obj = (Emp) context.getBean("emp");
System.out.println(obj);
}
}
When I run Test.java file it is showing this exception -
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'emp' defined in class path resource [com/springcore/autowire/Annotations/awannconfig.xml]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'address' defined in class path resource [com/springcore/autowire/Annotations/awannconfig.xml]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency
annotations: {}
Please help with this code as I cannot see any error.
The issue is coming due to parameterised constructor in the Address class whose constructor expects two parameters to be used to create a bean or object when you autowire it as there is no default constructor available.
Solution of the issue.
Keep Emp class as it is :
public class Emp {
private Address address;
public Address getAddress() {
return this.address;
}
#Autowired
#Qualifier("address")
public void setAddress(Address address) {
this.address = address;
}
public Emp(Address address) {
this.address = address;
}
#Override
public String toString() {
return "{" + " address='" + getAddress() + "'" + "}";
}
}
Keep Address class it is :
public class Address {
private String street;
private String city;
public String getStreet() {
return this.street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public Address(String street, String city) {
this.street = street;
this.city = city;
}
#Override
public String toString() {
return "{" + " street='" + getStreet() + "'" + ", city='" + getCity() + "'" + "}";
}
}
Update awannconfig.xml to this :
<?xml version="1.0" encoding="UTF-8"?>
<!-- We get this template from documentation -->
<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" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean class="com.springcore.autowire.Annotations.Emp" name="emp" />
<bean class="com.springcore.autowire.Annotations.Address" name="address">
<constructor-arg value="PA-24" type="String"/>
<constructor-arg value="Muradnagar" type="String"/>
</bean>
<!-- more bean definitions go here -->
</beans>
Output on my console.
{ address='{ street='PA-24', city='Muradnagar'}'}
Remember : Don't mix both constructor or setter injection as this will lead to confusion and unwanted errors.
Change bean configuration with constructor arg dependency injection, you missed that in emp bean definition. Change bean definition like below.
<bean class="com.springcore.autowire.Annotations.Emp" id="emp">
<constructor-arg ref = "address"/>
</bean>
<bean class="com.springcore.autowire.Annotations.Address" id="address">
<property name="street" value="PA-24" />
<property name="city" value="Muradnagar" />
</bean>
Im new to spring. I'm trying to autowire a bean using constructor using spring. Here is the code
<bean id="location" class="com.ibm.spring.Location">
<constructor-arg name="pincode" value="110976"></constructor-arg>
</bean>
<bean id="address" class="com.ibm.spring.Address">
<property name="id" value="2"></property>
<property name="street" value="shahjahan"></property>
</bean>
location class
public class Location {
private Address address;
private String pincode;
public void setAddress(Address address) {
this.address = address;
}
#Autowired
public Location(Address address, String pincode) {
super();
this.address = address;
this.pincode = pincode;
}
public void getTotalAddress() {
System.out.println(this.pincode + "::"+this.address);
}
}
Address class
public class Address {
private int id;
private String street;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = "Kkp";
}
#Override
public String toString() {
return "Address [id=" + id + ", street=" + street + "]";
}
Tester
public class SpringTester {
public static void main(String[] args) {
String configLoc = "com/ibm/spring/config/applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(configLoc);
Location l = (Location) ctx.getBean("location");
l.getTotalAddress();
}
}
I'm setting one of the field value through constructor arg. and class should be injected. WHat could be the problem here?
The error log says
Error creating bean with name 'location' defined in class path resource [com/ibm/spring/config/applicationContext.xml]: Unsatisfied dependency expressed through constructor parameter 0: Ambiguous argument values for parameter of type [com.ibm.spring.Address] - did you specify the correct bean references as arguments?
It seems like Location has two arguments so:
<bean id="location" class="com.ibm.spring.Location">
<constructor-arg name="pincode" value="110976"></constructor-arg>
<constructor-arg ref="address"></constructor-arg>
</bean>
For some reason, its not working. I searched and tried all the solutions found on the net. No dice. Looks like I am missing something.
My Beam:
#Entity
#Table(name="employees")
public class Person {
private Integer person_id;
private String name;
private String name2;
private String email;
private double phone;
private String desc;
#Id
#Max(value=500)
#Column (name="id")
public Integer getPerson_id() {
return person_id;
}
public void setPerson_id(Integer person_id) {
this.person_id = person_id;
}
#NotNull
#NotEmpty
#Column (name="fn")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="ln")
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
#Email
#Column (name="em", unique = true)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="phone")
public double getPhone() {
return phone;
}
public void setPhone(double phone) {
this.phone = phone;
}
#Column (name="de")
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String toString() {
return getPerson_id() + " - " + getName() + " - " + getName2() + " - " + getEmail();
}
}
Controller Method That handles POST:
#RequestMapping(value="/register", method = RequestMethod.POST, headers="Accept=*/*")
public String registerUer( #javax.validation.Valid Person registerForm, BindingResult br){
System.out.println( "Erros?" + br.hasErrors());
if ( br.hasErrors() ) {
System.out.println(br.getAllErrors());
}
System.out.println(registerForm);
return "thankyou";
}
home.jsp
<form:form action="register.htm" commandName="registerForm" method="post">
Name1: <form:input path="name"/><br />
Name2: <form:input path="name2"/><br />
Email: <form:input path="email"/><br />
Desc: <form:input path="desc" /><br />
Phone: <form:input path="phone" /><br />
<input type="submit" />
</form:form>
application context xml file:
<mvc:annotation-driven />
<context:component-scan base-package="com.springmvcsample"/>
<context:annotation-config/>
<import resource="hibernate_config.xml"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<!-- Turn off working out content type based on URL file extension, should fall back
to looking at the Accept headers -->
<property name="favorPathExtension" value="false" />
</bean>
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages" />
</bean>
I always get hasErrors() return false
I have hibernate validator (GA jar) file in my classspath. And I see this loaded:
INFO [Version] Hibernate Validator 4.2.0.Final
Am I missing something?
It works as expected if I remove JPA annotations (as I wanted to avoid further configuration for db) and use your form and controller code.
Definitely there is some missing piece, can you try by making a simple pojo with validation annotations and see.
the following xml is in a repository on a server:
<author xmlns="http://www..." xmlns:atom="http://www.w3.org/2005/atom">
<name>S. Crocker</name>
<address>None</address>
<affiliation></affiliation>
<email>None</email>
</author>
My model class:
#XmlRootElement(name = "author", namespace="http://www...")
#XmlAccessorType(XmlAccessType.FIELD)
public class Author {
#XmlAttribute(name="author")
private String author;
#XmlElement(name="name")
private String name;
#XmlElement(name="address")
private String address;
#XmlElement(name="affiliation")
private String affiliation;
#XmlElement(name="email")
private String email;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAffiliation() {
return affiliation;
}
public void setAffiliation(String affiliation) {
this.affiliation = affiliation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
According to a tutorial i saw i should use the #XmlSchema to a package-info.java
I create a class package-info.java but i don't know how to treat this.
Actually my problem is that i don't know how to use the corect annotations to bind the xml with the model class. The whole story is that i'm trying to retrieve an XML document from a repository, but i take null values. The problem as i saw here: JAXB: How to bind element with namespace
is that i don't use the correct annotations. Does anyone knows which are the correct annotations and how should i use them?
Below is an example of how you could map this use case:
package-info
I would use the package level #XmlSchema annotation to specify the namespace qualification. Specify the namespace to be your target namespace ("http://www.../ckp"). You want this namespace applied to all XML elements so specify elementFormDefault=XmlNsForm.QUALIFIED. The use xmlns to asssociate prefixes with your namespace URIs.
#XmlSchema(
namespace="http://www.../ckp",
elementFormDefault=XmlNsForm.QUALIFIED,
xmlns={
#XmlNs(prefix="", namespaceURI="http://www.../ckp"),
#XmlNs(prefix="atom", namespaceURI="http://www.w3.org/2005/atom"),
}
)
package forum10388261;
import javax.xml.bind.annotation.*;
Author
Below is what your Author class would look like. I have removed the unnecessary annotations (annotations that were equivalent to the default mapping).
package forum10388261;
import javax.xml.bind.annotation.*;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class Author {
#XmlAttribute
private String author;
private String name;
private String address;
private String affiliation;
private String email;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAffiliation() {
return affiliation;
}
public void setAffiliation(String affiliation) {
this.affiliation = affiliation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Demo
package forum10388261;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Author.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum10388261/input.xml");
Author author = (Author) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(author, System.out);
}
}
Output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<author xmlns:atom="http://www.w3.org/2005/atom" xmlns="http://www.../ckp">
<name>S. Crocker</name>
<address>None</address>
<affiliation></affiliation>
<email>None</email>
</author>
For More Information
http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
I've never needed to use the namespace parameter on #XmlRootElement, try leaving that off; also, you have #XmlAttribute specified for author, but there's no author in your example besides the tag name.
As for:
Actually my problem is that i don't know how to use the corect
annotations to bind the xml with the model class.
In your spring config you can do:
<oxm:jaxb2-marshaller id="jaxb2Marshaller">
<oxm:class-to-be-bound name="com.mycompany.Author"/>
<!-- ... -->
</oxm:jaxb2-marshaller>
Then inject the jaxb2Marshaller directly or use a MessageConverter like so:
<bean id="xmlConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<constructor-arg>
<ref bean="jaxb2Marshaller"/>
</constructor-arg>
<property name="supportedMediaTypes">
<list>
<bean class="org.springframework.http.MediaType">
<constructor-arg index="0" value="application"/>
<constructor-arg index="1" value="xml"/>
<constructor-arg index="2" value="UTF-8"/>
</bean>
</list>
</property>
</bean>
If you want to use spring's content negotiation, you could then use AnnotationMethodHandlerAdapter with the message converter:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="xmlConverter"/>
<!-- other converters if you have them, e.g. for JSON -->
</list>
</property>
</bean>
I have 2 entities User and Status. I can load users list and can see its sql(log) in console
(select this_.id as id0_0_,
this_.cl_point_id as cl2_0_0_,
this_.date_ll as date3_0_0_,
this_.date_reg as date4_0_0_,
this_.name as name0_0_,
this_.passw_salt as passw6_0_0_,
this_.status_id as status7_0_0_,
this_.passw as passw0_0_, this_.login
as login0_0_ from users this_)
.
But when I load Status the list is empty and there is no sql(log) in console. I can't find where is the problem?
User.java
package tj.eskhata.pos.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="users")
public class User implements DomainObject {
#Id
private Long id;
#Column(name="name")
private String fullname;
#Column(name="cl_point_id")
private Long clPointId;
#Column(name="login")
private String wiaUsername;
#Column(name="passw")
private String wiaPassword;
#Column(name="status_id")
private Long statusId;
#Column(name="date_reg")
private Date dateReg;
#Column(name="date_ll")
private Date dateLl;
#Column(name="passw_salt")
private String passwSalt;
public User() {
}
public User(String username, String password, String fullname,
boolean isAdmin) {
this.id=Long.valueOf(1);
this.wiaUsername = username;
this.wiaPassword = password;
this.fullname = fullname;
}
public String getFullname() {
return fullname;
}
public String getWiaPassword() {
return wiaPassword;
}
public String getWiaUsername() {
return wiaUsername;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public void setWiaPassword(String password) {
this.wiaPassword = password;
}
public void setWiaUsername(String username) {
this.wiaUsername = username;
}
public Long getId() {
return id;
}
public Long getClPointId() {
return clPointId;
}
public Long getStatusId() {
return statusId;
}
public Date getDateReg() {
return dateReg;
}
public Date getDateLl() {
return dateReg;
}
public String getPasswSalt() {
return passwSalt;
}
public void getClPointId(Long clPointId_) {
this.clPointId=clPointId_;
}
public void setStatusId(Long statusId_) {
this.statusId=statusId_;
}
public void setDateReg(Date dateReg_) {
this.dateReg=dateReg_;
}
public void setDateLl(Date dateLl_) {
this.dateLl=dateLl_;
}
public void setPasswSalt(String passwSalt_) {
this.passwSalt=passwSalt_;
}
public boolean isAdmin() {
return false;
}
}
Status.java
package tj.eskhata.pos.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="status")
public class Status implements DomainObject {
public Status() {
}
public Status(Long id) {
this.id = id;
}
public Status(Long id, String code, String name, String fullName,
String color) {
this.id = id;
this.code = code;
this.name = name;
this.fullName = fullName;
this.color = color;
}
#Id
private Long id;
public void setId( Long id_) {
this.id=id_;
}
public Long getId() {
return this.id;
}
#Column(name = "code")
private String code;
public void setCode( String code_) {
this.code=code_;
}
public String getCode() {
return this.code;
}
#Column(name = "name")
private String name;
public void setName( String name_) {
this.name=name_;
}
public String getName() {
return this.name;
}
#Column(name = "full_name")
private String fullName;
public void setFullName( String fullName_) {
this.name=fullName_;
}
public String getFullName() {
return this.fullName;
}
#Column(name = "color")
private String color;
public void setColor( String color_) {
this.color=color_;
}
public String getColor() {
return this.color;
}
}
*
UserDaoImpl.java:
package tj.eskhata.pos.dao.hibernate;
import tj.eskhata.pos.dao.UserDao;
import tj.eskhata.pos.domain.User;
public class UserDaoImpl extends AbstractHibernateDaoImpl<User>
implements UserDao {
public UserDaoImpl() {
super(User.class);
}
}
StatusDaoImpl.java:
package tj.eskhata.pos.dao.hibernate;
import tj.eskhata.pos.dao.StatusDao;
import tj.eskhata.pos.domain.Status;
public class StatusDaoImpl extends AbstractHibernateDaoImpl<Status>
implements StatusDao {
public StatusDaoImpl() {
super(Status.class);
}
}
UserDao.java:
package tj.eskhata.pos.dao;
import tj.eskhata.pos.domain.User;
public interface UserDao extends Dao<User> {
}
StatusDao.java:
package tj.eskhata.pos.dao;
import tj.eskhata.pos.domain.Status;
public interface StatusDao extends Dao<Status> {
}
AbstractHibernateDaoImpl.java:
package tj.eskhata.pos.dao.hibernate;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import tj.eskhata.pos.dao.Dao;
import tj.eskhata.pos.domain.DomainObject;
public abstract class AbstractHibernateDaoImpl<T extends DomainObject>
implements Dao<T> {
private Class<T> domainClass;
private SessionFactory sf;
public AbstractHibernateDaoImpl(Class<T> domainClass) {
this.domainClass = domainClass;
}
public SessionFactory getSessionFactory() {
return sf;
}
public void setSessionFactory(SessionFactory sf) {
this.sf = sf;
}
public void delete(T object) {
getSession().delete(object);
}
#SuppressWarnings("unchecked")
public T load(long id) {
return (T) getSession().get(domainClass, id);
}
public void save(T object) {
getSession().saveOrUpdate(object);
}
#SuppressWarnings("unchecked")
public List<T> findAll() {
Criteria criteria = getSession().createCriteria(domainClass);
List<T> r=(List<T>) criteria.list();
return r;
}
public int countAll() {
Criteria criteria = getSession().createCriteria(domainClass);
criteria.setProjection(Projections.rowCount());
return (Integer) criteria.uniqueResult();
}
public Session getSession() {
// presumes a current session, which we have through the
// OpenSessionInViewFilter; doesn't work without that
return sf.getCurrentSession();
}
}
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jndi="http://www.springframework.org/schema/jndi"
xmlns:util="http://www.springframework.org/schema/util"
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-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/jndi
http://www.springframework.org/schema/jndi/spring-jndi.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:application.properties</value>
</property>
<property name="systemPropertiesModeName">
<value>SYSTEM_PROPERTIES_MODE_OVERRIDE</value>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass">
<value>${jdbc.driver}</value>
</property>
<property name="jdbcUrl">
<value>${jdbc.url}</value>
</property>
<property name="user">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<property name="minPoolSize">
<value>${c3p0.minPoolSize}</value>
</property>
<property name="maxPoolSize">
<value>${c3p0.maxPoolSize}</value>
</property>
<property name="checkoutTimeout">
<value>20000</value>
</property>
<property name="maxIdleTime">
<value>${c3p0.maxIdleTime}</value>
</property>
<property name="idleConnectionTestPeriod">
<value>${c3p0.idleConnectionTestPeriod}</value>
</property>
<property name="automaticTestTable">
<value>${c3p0.automaticTestTable}</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>tj.eskhata.pos.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven />
<bean id="wicketApplication"
class="tj.eskhata.pos.PosApplication">
</bean>
<bean id="UserDao"
class="tj.eskhata.pos.dao.hibernate.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="CountryDao"
class="tj.eskhata.pos.dao.hibernate.CountryDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="StatusDao"
class="tj.eskhata.pos.dao.hibernate.StatusDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="GenericDao"
class="tj.eskhata.pos.dao.hibernate.GenericDaoImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="DiscountsService" class="tj.eskhata.pos.services.DiscountsServiceImpl">
<property name="userDao" ref="UserDao" />
<property name="countryDao" ref="CountryDao" />
<property name="statusDao" ref="StatusDao" />
<property name="genericDao" ref="GenericDao" />
</bean>
</beans>
DiscountService:
package tj.eskhata.pos.services;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import tj.eskhata.pos.domain.Country;
import tj.eskhata.pos.domain.Status;
import tj.eskhata.pos.domain.User;
public interface DiscountsService {
<T> T load(Class<T> type, long id);
List<User> findAllUsers();
void saveUser(User user);
void deleteUser(User user);
List<Country> findAllCountries();
void saveCountry(Country country);
void deleteCountry(Country country);
List<Status> findAllStatuses();
void saveStatus(Status status);
void deleteStatus(Status status);
}
package tj.eskhata.pos.services;
import java.util.List;
import tj.eskhata.pos.dao.CountryDao;
import tj.eskhata.pos.dao.GenericDao;
import tj.eskhata.pos.dao.StatusDao;
import tj.eskhata.pos.dao.UserDao;
import tj.eskhata.pos.domain.Country;
import tj.eskhata.pos.domain.Status;
import tj.eskhata.pos.domain.User;
public class DiscountsServiceImpl implements DiscountsService {
private UserDao userDao;
private CountryDao countryDao;
private StatusDao statusDao;
private GenericDao genericDao;
public DiscountsServiceImpl() {
}
public <T> T load(Class<T> type, long id) {
return genericDao.load(type, id);
}
public List<User> findAllUsers() {
return userDao.findAll();
}
public void saveUser(User user) {
userDao.save(user);
}
public void deleteUser(User user) {
userDao.delete(user);
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public List<Country> findAllCountries() {
return countryDao.findAll();
}
public void saveCountry(Country country) {
countryDao.save(country);
}
public void deleteCountry(Country country) {
countryDao.delete(country);
}
public CountryDao getCountryDao() {
return countryDao;
}
public void setCountryDao(CountryDao countryDao) {
this.countryDao = countryDao;
}
public List<Status> findAllStatuses() {
return statusDao.findAll();
}
public void saveStatus(Status status) {
statusDao.save(status);
}
public void deleteStatus(Status status) {
statusDao.delete(status);
}
public StatusDao getStatusDao() {
return statusDao;
}
public void setStatusDao(StatusDao statusDao) {
this.statusDao = statusDao;
}
public GenericDao getGenericDao() {
return genericDao;
}
public void setGenericDao(GenericDao genericDao) {
this.genericDao = genericDao;
}
}
The Status entity looks fine (it has an #Entity annotation, it has a default no-arg constructor, it has an #Id), I can't spot anything obvious.
So I would:
double check the startup logs to check for any complaint.
use the Hibernate Console (if you are using Eclipse) or any equivalent to load the Status using raw HQL or Criteria.
write a unit test anyway.
Oh, by the way, this is unrelated but you shouldn't have such things in your User entity:
#Column(name="status_id")
private Long statusId;
These Long look like foreign keys. When using an ORM, you should have objects and associations between objects, not ids. Something like this:
#ManyToOne
private Status status;
Same remark for clPointId.
You are IMHO thinking "too relational" and "not enough object". I might be wrong but having foreign key attributes in an entity is a strong hint.
I have changed #Column(name="status_id") private Long statusId; to #ManyToOne private Status status; Now I receiving the ERROR: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: #OneToOne or #ManyToOne on tj.eskhata.pos.domain.User.status references an unknown entity: tj.eskhata.pos.domain.Status
This message clearly shows that something goes wrong with Status that isn't recognized as an Entity (and thus can't be referenced in an association, preventing the session factory from being instantiated). This is usually due to a configuration or mapping problem. So:
Do you declare entities somewhere (in hibernate.cfg.xml or in persistence.xml)? If yes, did you declare Status? If you are using classpath scanning, is Status scanned?
Double-check the mapping, check that the column names really exist (it's unclear if you are using an existing physical model).
Activate logging (Spring Logging, Hibernate Logging), this is helpful during development and will help to find the problem.