Java - Hibernate Exception - Feedback cannot be mapped [ from Feedback ] - java

I am new to Hibernate. Recently, I was trying simple example to connect my UI with Database using Spring and Hibernate.
I am able to successfully call a method to fetch the data through my controller, service etc using REST.
But I am encountering below error,whenever I run the application.
Here "Feedback" is the name of Table in Database as well as the same name of my Pojo Java class.
Note : Giving different names to table and Java class also results in same error.
org.springframework.orm.hibernate3.HibernateQueryException: Feedback
is not mapped [from Feedback]; nested exception is
org.hibernate.hql.ast.QuerySyntaxException: Feedback is not mapped
[from Feedback]
Java Pojo:-
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Feedback")
public class Feedback {
private int id;
private String title;
private String content;
private String name;
#Id
#GeneratedValue
#Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="title", nullable=false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="content", nullable=false)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Column(name="name", nullable=false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Feedback [id=" + id + ", title=" + title + ", content="
+ content + ", name=" + name + "]";
}
}
FeedbackDAO :-
#Repository
public class FeedbackDAO implements IFeedbackDAO {
private HibernateTemplate hibernateTemplate;
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#SuppressWarnings("unchecked")
public List<Feedback> getFeedbackList() {
// This line causes that error.
return hibernateTemplate.find("from Feedback");
}
...
...
}
Configuration made in db-config.xml
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory"><ref local="sessionFactory"/></property>
</bean>
What could be causing this ?
Do am I missing something here ?
Thanks

You might have missed a thing in sessionFactory definition.
<bean id="sessionFactory" ...>
...
<property name="annotatedClasses">
<list>
<value><java package name here>.Feedback</value>
</list>
</property>
...
</bean>

Related

Hibernate doesn't creating table based on entity

After starting the program (launching TomCat) there are no tables created in the schema, but the table "player" has to be created automatically.
I checked hibernate config, but can't find where is the problem.
I've tried changing hbm2ddl.auto to hibernate.hbm2ddl.auto (also create, create-drop etc.) but it didn't help.
If there are any ideas, please let me know. Thanks.
Entity class:
package com.game.entity;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(schema = "rpg", name = "player")
public class Player {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name", length = 12, nullable = false)
private String name;
#Column(name = "title", length = 30, nullable = false)
private String title;
#Column(name = "race", nullable = false)
#Enumerated(EnumType.ORDINAL)
private Race race;
#Column(name = "profession", nullable = false)
#Enumerated(EnumType.ORDINAL)
private Profession profession;
#Column(name = "birthday", nullable = false)
private Date birthday;
#Column(name = "banned", nullable = false)
private Boolean banned;
#Column(name = "level", nullable = false)
private Integer level;
public Player() {
}
public Player(Long id, String name, String title, Race race, Profession profession, Date birthday, Boolean banned, Integer level) {
this.id = id;
this.name = name;
this.title = title;
this.race = race;
this.profession = profession;
this.birthday = birthday;
this.banned = banned;
this.level = level;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Race getRace() {
return race;
}
public void setRace(Race race) {
this.race = race;
}
public Profession getProfession() {
return profession;
}
public void setProfession(Profession profession) {
this.profession = profession;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Boolean getBanned() {
return banned;
}
public void setBanned(Boolean banned) {
this.banned = banned;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
}
Repository class:
package com.game.repository;
import com.game.entity.Player;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.NativeQuery;
import org.springframework.stereotype.Repository;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Optional;
#Repository(value = "db")
public class PlayerRepositoryDB implements IPlayerRepository {
private final SessionFactory sessionFactory;
public PlayerRepositoryDB() {
Configuration configuration = new Configuration().configure().addAnnotatedClass(Player.class);
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
#Override
public List<Player> getAll(int pageNumber, int pageSize) {
try(Session session = sessionFactory.openSession()){
NativeQuery<Player> nativeQuery = session.createNativeQuery("SELECT * FROM rpg.player", Player.class);
nativeQuery.setFirstResult(pageNumber * pageSize);
nativeQuery.setMaxResults(pageSize);
return nativeQuery.list();
}
}
Hibernate configuration:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/rpg</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Full project code with pom.xml is available by link:
https://github.com/gamlethot/project-hibernate-1
1-Hibernate does not recognize your repository. You should not mark repo classes as #Repository because they are not interfaces and in your example they are working like a service. So they can be #Service.
2-Do not implement IPlayerRepository. Mark it as #Repository and just autowire it to your service classes (or use constructor injection and just use like a variable)
Like:
#Service
public class PlayerRepositoryDB {
private IPlayerRepository playerRepository;
public PlayerRepositoryDB (IPlayerRepository playerRepository){ //CONSTRUCTOR
this.playerRepository = playerRepository;...
3- DB repository classes are implementing IPlayerRepository but it must be marked as #Repository and It should extend either CrudRepository or JpaRepository (which extends CrudRepository already).
Like:
#Repository
public interface IPlayerRepository extends JpaRepository<Player, Long> {
//Here are the methods;
}
Here, the Long is the type of primary key of Player class.
Hibernate XML:
<property name="hibernate.connection.CharSet">utf8mb4</property>
<property name="hibernate.connection.characterEncoding">UTF-8</property>
<property name="hibernate.connection.useUnicode">true</property>
Connection url:
db.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&character_set_server=utf8mb4
As a side note I would like to make one clarification that UTF-8 is the character encoding while utf8mb4 is a character set that MySQL supports. MySQL's utf8mb4 is a superset to MySQL's utf8.
Spring/Hibernate filter:
<form accept-charset="UTF-8">
Problem solved.
It was because of javax.persistence.; import instead of
jakarta.persistence. in entity class.

Not able to autowire a bean using constructor in Spring

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>

Repeated column in mapping for entry error

I am doing a simple hibernate program in which I use Attribute override and Embedded object keys and I got this error:
Exception in thread "main" org.hibernate.MappingException: Repeated
column in mapping for entity: com.hibernate.Model.Employee column:
pincode (should be mapped with insert="false" update="false")
Employee.java
package com.hibernate.Model;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String LastName;
private String email;
private String phoneNo;
#Embedded
#AttributeOverrides({
#AttributeOverride (name="City" , column=#Column(name="OFFICE_CITY")),
#AttributeOverride (name="State", column=#Column(name="OFFICE_STATE")),
#AttributeOverride (name="Country", column=#Column(name="OFFICE_COUNTRY")),
#AttributeOverride (name="pinCode", column=#Column(name="OFFICE_PINCODE"))})
private Address officeAddress;
#Embedded
private Address homeAddress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Address getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
}
Address.java
package com.hibernate.Model;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String City;
private String State;
private String Country;
private String pincode;
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
Hibernate.jsp
package com.hibernate.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.Model.Address;
import com.hibernate.Model.Employee;
public class HibernateTest {
public static void main(String[] args) {
Employee emp = new Employee();
Address addr=new Address();
emp.setFirstName("Vikas");
emp.setLastName("Bhardwaj");
emp.setEmail("bhardwajvikas93#gmail.com");
emp.setPhoneNo("9741178304");
addr.setCity("MEHRE");
addr.setCountry("INDIA");
addr.setState("HIMACHAL");
addr.setPincode("174305");
emp.setHomeAddress(addr);
Address addr2 = new Address();
addr2.setCity("Bangalore");
addr2.setCountry("INDIA");
addr2.setState("KARNATKA");
addr2.setPincode("560008");
emp.setOfficeAddress(addr2);
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session ssn = sf.openSession();
ssn.beginTransaction();
ssn.save(emp);
ssn.getTransaction().commit();
ssn.close();
}
}
cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/HibernateDb</property>
<property name="connection.username">root</property>
<property name="connection.password">vikas</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="com.hibernate.Model.Employee"/>
<mapping class="com.hibernate.Model.Address"/>
</session-factory>
</hibernate-configuration>
In this program by embedable, I am printing both member variables in one table.
The task is with address class, I am printing two addresses. One is for home address and one is for office address by using AttributeOverrides but it gives me the error mentioned above.
You need to specify a valid property name pincode
#AttributeOverride (name="pinCode", column=#Column(name="OFFICE_PINCODE"))
need to change to
#AttributeOverride (name="pincode", column=#Column(name="OFFICE_PINCODE"))
Try to specify #AttributeOverrides for homeAddress, if it will not help.

XML binding with the use of JAXB and Spring-MVC

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>

Java, Hibernate,Spring

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.

Categories

Resources