Spring + Hibernate, can not read xml error - java

I am a newbie in Spring + Hibernate, but I have worked on this problem for last one day. I still can not figure out what is the root cause, and what should I do. So, thank you in advance if any one can give me some advice.
Here is a problem, I just write a simple test class, but when I ran, there is an exception:
??: Exception encountered during context initialization - cancelling refresh >attempt: org.springframework.beans.factory.BeanCreationException: Error >creating bean with name 'sessionFactory' defined in class path resource >>>>>>>[ApplicationContext.xml]: Invocation of init method failed; nested exception is >org.hibernate.InvalidMappingException: Unable to read XML
Exception in thread "main" >org.springframework.beans.factory.BeanCreationException: Error creating bean >with name 'sessionFactory' defined in class path resource >[ApplicationContext.xml]: Invocation of init method failed; nested exception is> org.hibernate.InvalidMappingException: Unable to read XML
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.(ClassPathXmlApplicationContext.java:83)
at com.xw.test.Test.main(Test.java:30)
And here is the class source code:
package com.domain;
import java.util.Date;
public class Employee {
private Integer id;
private String name;
private String email;
private java.util.Date hiredate;
private Float salary;
public Float getSalary() {
return salary;
}
public void setSalary(Float salary) {
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public java.util.Date getHiredate() {
return hiredate;
}
public void setHiredate(java.util.Date hiredate) {
this.hiredate = hiredate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Employee( String name, String email, Date hiredate,
Float salary) {
this.name = name;
this.email = email;
this.hiredate = hiredate;
this.salary = salary;
}
public Employee(){
}
}
And here is the Employee.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-mapping package="com.domain">
<class name="Employee" table="employee">
<id name="id" type="java.lang.Integer">
<generator class="native" ></generator>
</id>
<property name="email" type="java.lang.String" >
<column name="email" length="64"/>
</property>
<property name="hiredate" type="java.util.Date">
<column name="hiredate" />
</property>
<property name="name" type="java.lang.String">
<column name="name"/>
</property>
<property name="salary" type="java.lang.Float">
<column name="salary"/>
</property>
</class>
</hibernate-mapping>
And here is the ApplicationContext.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<bean id="testService" class="com.xw.test.TestService">
<property name="name" value="XingWang"/>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#127.0.0.1:1521:orcl"/>
<property name="username" value="scott"/>
<property name="password" value="111111"/>
<property name="initialSize" value="3"/>
<property name="maxActive" value="500"/>
<property name="maxIdle" value="2"/>
<property name="minIdle" value="1"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/domain/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.OracleDialect
</value>
</property>
</bean>
</beans>
And the pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>myssh</groupId>
<artifactId>myssh</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebRoot</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.2.Final</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
</dependencies>
And here is the smiple test class source code:
/**
*
*/
package com.xw.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.domain.Employee;
/**
* #author Administrator
*
*/
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
SessionFactory sf = (SessionFactory) ac.getBean("sessionFactory");
Session s = sf.openSession();
Employee employee = new Employee( "aa", "aa.sohu#com", new java.util.Date(),
(float) 234.56) ;
Transaction tx = s.beginTransaction();
s.save(employee);
tx.commit();
}
}
Thank you so much for any advice!

The properties should be declared like below inside your sessionFactory Bean.
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
so your sessionFactory bean would be like below.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>com/domain/Employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
</props>
</property>

sometimes there is a chance of cant pick ur config files because of compiler dont konw which file shoul it take for configuration.so for this reason u should explicitly import those config file via 2 methods as i know
1)by using class
#Configuration
#ImportResource(value = {"classpath:{filename-within-resource}/Employee.hbm.xml"},"classpath:{filename-within-resource}/ApplicationContext.cfg.xml")
public class CommonSolutionConfig {
}
2)by using xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<import resource="classpath:{filename-within-resource}/Employee.hbm.xml"/>
<import resource="classpath:{filename-within-resource}/ApplicationContext.cfg.xml"/>
</beans>
hopefully it will solve ur problem

Related

How to insert into HSQL from a thymeleaf form

Controller
package com.hellokoding.hello.web;
import com.hellokoding.hello.pojo.*;
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 org.springframework.web.bind.annotation.RequestParam;
import com.hellokoding.hello.dao.*;
#Controller
public class HelloController {
#Autowired
StudentDAO studentDao;
#RequestMapping("/")
public String index() {
return "input";
}
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(#RequestParam(value = "name", required = false, defaultValue = "World") String name,
Model model) {
model.addAttribute("name", name);
return "hello";
}
#RequestMapping(value = "/studentRegister", params = {"save"})
public String saveSeedstarter(final Student student, final BindingResult bindingResult, final ModelMap model) {
if (bindingResult.hasErrors()) {
return "input";
}
model.addAttribute("student", student);
studentDao.saveStudent(student);
return "result";
}
#ModelAttribute("student")
public Student getStudent(){
return new Student();
}
/*
* #RequestMapping(value = "/studentRegister", method = RequestMethod.POST)
* public String index(#RequestParam(value="save") Student student, Model
* model) { model.addAttribute("student", student); return "hello"; }
*/
}
Hsql db in
The url is jdbc:hsqldb:mem:mydb
I dunno where the db files will be??. If i open in database manager then i cannot see the student database. Help me to fix this
I have the form
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Spring Thyme Seed Starter Manager</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2>Add new student</h2>
<form action="#" th:action="#{/studentRegister}"
th:object="${student}" method="post">
<input type="text" th:field="*{firstName}"/>
<input type="text" th:field="*{lastName}"/>
<input type="submit" name="save" value="save"/>
</form>
</body>
</html>
Web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Hello Spring MVC</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
appconfig-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<import resource="appconfig-mvc.xml"/>
<!-- Scans within the base package of the application for #Component classes to configure as beans -->
<context:component-scan base-package="com.hellokoding.hello.*"/>
<context:property-placeholder location="classpath:application.properties"/>
</beans>
appconfig-mvc.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>WEB-INF/configuration.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${jdbc.driver.className}</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>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="packagesToScan" value="com.hellokoding.hello.pojo" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<tx:annotation-driven />
</beans>
I need to submit the form i have added the it to student model attribute in controller. I need to insert this data into student db of HSQL. How to proceed with modifications in spring xml.
I have included a persistence.xml under resources/META-INF
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="manager" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.hellokoding.hello</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:mydb"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
configuration.properties
jdbc.driver.className=org.hsqldb.jdbcDriver
jdbc.url=jdbc:hsqldb:mem:mydb
jdbc.username=sa
jdbc.password=
jdbc.hibernate.dialect=org.hibernate.dialect.HSQLDialect
DAO interface
package com.hellokoding.hello.dao;
import java.util.List;
import com.hellokoding.hello.pojo.Student;
public interface StudentDAO {
public void saveStudent(Student student);
public List<Student> getAllStudents(Student student);
public Student getStudentById(String studentId);
public void deleteStudent(Student student);
}
DAO implementation
package com.hellokoding.hello.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.hellokoding.hello.pojo.Student;
//This will make easier to autowired
#Repository("StudentDAO")
#Transactional
public class StudentDAOImpl implements StudentDAO {
private HibernateTemplate hibernateTemplate;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Transactional(readOnly = false)
public void saveStudent(Student student) {
System.out.println("Inside");
hibernateTemplate.saveOrUpdate(student);
}
#Transactional(readOnly = false)
public void deleteStudent(Student student) {
hibernateTemplate.delete(student);
}
#SuppressWarnings("unchecked")
public List<Student> getAllStudents(Student student) {
return (List<Student>) hibernateTemplate.find("from " + Student.class.getName());
}
public Student getStudentById(String studentId) {
return hibernateTemplate.get(Student.class, studentId);
}
}
I have tried with hibernate and i was trying to insert into the db.
Student Bean
package com.hellokoding.hello.pojo;
import javax.persistence.*;
import java.io.Serializable;
//import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name = "student_table")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
public static long getSerialversionuid() {
return serialVersionUID;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name = "first_name", nullable = false)
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "last_name", nullable = false)
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Student(){
}
public Student(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
}
The id is also not generating and its not inserting the HSQL db table called student_table
Pom.xml
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hellokoding</groupId>
<artifactId>hello</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Hello Spring MVC</name>
<url>http://maven.apache.org</url>
<properties>
<jdk.version>1.8</jdk.version>
<spring.version>4.1.6.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<junit.version>3.8.1</junit.version>
<logback.version>1.1.3</logback.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${thymeleaf.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency>
<dependency>
<groupId>hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>1.8.0.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.5.Final</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.8.5.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<!-- embedded Jetty server, for testing -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.11.v20150529</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>

Spring BeanCreationException: Error creating bean with name 'accountDaoBean'

[enter image description here][1]
Account.java
package com.hibernateWithSpring;
public class Account {
private int accountNumber;
private String owner;
private double balance;
public Account(){
}
public Account(int accountNumber, String owner, double balance) {
this.accountNumber=accountNumber;
this.owner= owner;
this.balance=balance;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
AccountClient.java
package com.hibernateWithSpring;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class AccountClient {
public static void main(String[] args){
ApplicationContext context=new FileSystemXmlApplicationContext("bin/beans.xml");
AccountDao accountdao = context.getBean("accountDaoBean",AccountDao.class);
accountdao.createAccount(110, "varun",1000);
accountdao.createAccount(111, "vicky",1200);
System.out.println("account created");
accountdao.updateBalance(111,2222);
System.out.println("account updated");
accountdao.deleteAccount(111);
System.out.println("account deleted");
List<Account> account= accountdao.getAllAccount();
for(int i=0;i<account.size();i++){
Account acc=account.get(i);
System.out.println(acc.getAccountNumber()+":"+acc.getOwner()+":"+acc.getBalance());
}
}
}
AccountDao.java
package com.hibernateWithSpring;
import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class AccountDao extends HibernateDaoSupport
{
public void createAccount(int accountNumbeer, String owner, double balane){
Account account= new Account(accountNumbeer,owner,balane);
getHibernateTemplate().save(account);
}
public void updateBalance(int accountNumber, double newBalance){
Account account= getHibernateTemplate().get(Account.class, accountNumber);
if(account !=null){
account.setBalance(newBalance);
}
getHibernateTemplate().update(account);
}
public void deleteAccount(int accountNumber){
Account account=getHibernateTemplate().get(Account.class, accountNumber);
if(account!=null){
getHibernateTemplate().delete(account);
}
}
#SuppressWarnings("unchecked")
public List<Account> getAllAccount()
{
return getHibernateTemplate().find("from Account");
}
}
Account.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.hibernateWithSpring.Account" table="account">
<id name="accountNumber" column="account_number" type="int"></id>
<property name="owner" column="owner" type="string"></property>
<property name="balance" column="balance" type="double"></property>
</class>
</hibernate-mapping>
beans.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="accountDaoBean" class="com.hibernateWithSpring.AccountDao">
<property name="hibernateTemplate" ref="hibernateTemplateBean"></property>
</bean>
<bean id="hibernateTemplateBean" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sfBean"></property>
</bean>
<bean id="sfBean" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSourceBean"></property>
<property name="mappingResources">
<value>com/hibernateWithSpring/Account.hbm.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="dataSourceBean" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/accountdb"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
</beans>
My db Details are correct But I have no idea why i am getting this error:-
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountDaoBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Cannot resolve reference to bean 'hibernateTemplateBean' while setting bean property 'hibernateTemplate'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplateBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Cannot resolve reference to bean 'sfBean' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sfBean' defined in file [E:\new project\marsWorkspase\SpringProgram\bin\beans.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager
Things you need to fix:
1 - put the JAR (javaee-api) in your LIB folder
http://mvnrepository.com/artifact/javax/javaee-api/7.0
2 - if you are using Maven, add the following dependency
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0</version>
</dependency>
3 - Configure your artifact and include this jar, allowing to be deployed
4 - Put the javaee-api jar in your tomcat/jboss lib folder

Getting Exception while connecting Spring to hibernate using H2 database

I am getting below exception:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mysessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.naveen.java.InsertTest.main(InsertTest.java:12)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:508)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:677)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417)
... 12 more
Caused by: org.dom4j.DocumentException: Connection timed out: connect Nested exception: Connection timed out: connect
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:499)
... 16 more
Below is employee .java
package com.naveen.java;
import javax.persistence.Id;
public class Employee {
private int id;
private String name;
private int salary;
private String LASTNAME ;
public String getLASTNAME() {
return LASTNAME;
}
public void setLASTNAME(String lASTNAME) {
this.LASTNAME = lASTNAME;
}
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(int salary) {
this.salary = salary;
}
}
below is employeedao.java
package com.naveen.java;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class EmployeeDao {
HibernateTemplate template;
public void setTemplate(HibernateTemplate template) {
this.template = template;
}
public void saveEmployee(Employee e){
template.save(e);
}
public void updateEmployee(Employee e){
template.update(e);
}
public void deleteEmployee(Employee e){
template.delete(e);
}
}
below is inserttest.java
package com.naveen.java;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class InsertTest {
public static void main(String[] args) {
ApplicationContext con=new ClassPathXmlApplicationContext("applicationContext.xml");
//Resource r=new ClassPathResource("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)con.getBean("d");
Employee e=new Employee();
e.setId(147);
e.setName("kumar");
e.setSalary(70000);
//dao.saveEmployee(e);
dao.updateEmployee(e);
}
}
below are both the 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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:~/test"/>
<property name="username" value="sa"/>
<property name="password" value="123"/>
</bean>
<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee-hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="com.naveen.EmployeeDao">
<property name="template" ref="template"></property>
</bean> </beans>
2nd xml mapping
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.naveen.java.Employee" table="EMP558">
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="NAME" type="string"/>
<property name="lastName" column="LASTNAME" type="string"/>
<property name="salary" column="salary" type="double"/>
</class>
</hibernate-mapping>
I have tried to link through JDBC and it's working fine.
salary field has int type, but there is double in the hibernate mapping
This might be caused because the hibernate trying retrieving the dtd file. so, the workaround could be :
change the value of the dtd from that to "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"
Create your own function to parse the configuration then passed to the hibernate like this
public static Document parseConfiguration(String resourcePath) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false); <-- the magic is here
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(builder.getClass().getResourceAsStream(resourcePath));
}
I am not getting the error you are getting, though I fixed lot of errors in your entity (properties defined in the mapping file not present in the entity). I have reached the step where it is trying to insert the record, so I am well past the stage where you are getting the error.
By looking into the hibernate source file (org.hibernate.cfg.Configuration.addInputStream(Configuration.java:499)) which is throwing error, hibernate is not able to reach your mapping xml file.
Please double check if the mapping file is at proper location and also readable.
Also make sure you have correct version of hibernate jar in the classpath.

Spring + Hibernate + Maven org.hibernate.MappingException: AnnotationConfiguration instance is required

I am new to Spring so as to Hibernate frameworks. The task is to create a project with both front and back ends, but for now I would like to focus on DB connection.
I have MySQL database on localhost within my MySQL server. There is a simple application which needs to create clients, orders and search for them in the DB, so the task is trivial. Yet, I encounter the following ecxeption:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory ee.st.running.dao.ClientDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="ee.st.running.model.Client"/>
I tried some manipulations, read many similar issues here, which led me to other exceptions much like this.
My config.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scan base-package=".*" />
<tx:annotation-driven/>
<context:annotation-config />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/sqlconnection" />
<property name="username" value="admin" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>ee.st.running.model.Client</value>
<value>ee.st.running.dao.ClientDAOImpl</value>
<value>ee.st.running.model.Order</value>
<value>ee.st.running.dao.OrderDAOImpl</value>
</list>
</property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
<bean id = "client" class = "ee.st.running.model.Client">
<property name="clientDAO" ref = "ClientDAO"></property>
</bean>
<bean id = "clientDAO" class = "ee.st.running.dao.ClientDAOImpl">
<property name="sessionFactory" ref = "sessionFactory"></property>
</bean>
<bean id = "order" class = "ee.st.running.model.Order">
<property name="orderDAO" ref = "OrderDAO"></property>
</bean>
<bean id = "orderDAO" class = "ee.st.running.dao.OrderDAOImpl">
<property name="sessionFactory" ref = "sessionFactory"></property>
</bean>
</beans>
And here is the project structure:
And here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ee.st.running.aktorstask</groupId>
<artifactId>aktorstask</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.2.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<properties>
<spring.version>3.2.3.RELEASE</spring.version>
</properties>
</project>
And the classes:
Client
package ee.st.running.model;
//import java.util.List;
//import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
//import javax.persistence.OneToMany;
import javax.persistence.Table;
import ee.st.running.dao.ClientDAOInterface;
import ee.st.running.dao.ClientDAOImpl;
#Entity
#Table(name = "client")
public class Client implements ClientInterface {
private Order o;
ClientDAOInterface ClientDAOInterface;
#Id
#GeneratedValue
private int id;
#Column (name = "name")
private String name;
#Column (name = "surename")
private String surename;
#Column (name = "address")
private String address;
#Column (name = "phone_number")
private long phoneNumber;
#Column (name = "id_code")
private long idCode;
//#OneToMany(mappedBy = «client», fetch = FetchType.LAZY)
public void makeorder() {
o.newOrder();
}
// getters nd setters
public Order getO() {
return o;
}
public void setO(Order o) {
this.o = o;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurename() {
return surename;
}
public void setSurename(String surename) {
this.surename = surename;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public long getIdCode() {
return idCode;
}
public void setIdCode(int idCode) {
this.idCode = idCode;
}
// ctor
public Client ()
{
}
public void setClientInfDAO (ClientDAOInterface ClientDAOInterface)
{
this.ClientDAOInterface = ClientDAOInterface;
}
public void save(Client client) {
ClientDAOInterface.save(client);
}
public void update(Client client) {
ClientDAOInterface.update(client);
}
public void remove(Client client) {
ClientDAOInterface.remove(client);
}
}
ClientInterface:
package ee.st.running.model;
public interface ClientInterface {
public void makeorder ();
public void save(Client client);
public void update (Client client);
public void remove (Client client);
}
ClientDAOInterface:
package ee.st.running.dao;
import java.util.List;
import ee.st.running.model.Client;
public interface ClientDAOInterface {
public void removeClient (long id);
public List<Client> listClient();
public void save (Client client);
public void update (Client client);
public void remove (Client client);
}
ClientDAOImpl:
package ee.st.running.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import ee.st.running.model.Client;
#Repository
public class ClientDAOImpl extends HibernateDaoSupport implements ClientDAOInterface {
#Autowired
private SessionFactory sessionFactory;
public void AddClient(Client client) {
sessionFactory.getCurrentSession().save(client);
}
public void removeClient(long id) {
Client client = (Client) sessionFactory.getCurrentSession().load(Client.class, id);
if (null != client) {
sessionFactory.getCurrentSession().delete(client);
}
}
#SuppressWarnings("unchecked")
public List<Client> listClient() {
return sessionFactory.getCurrentSession().createQuery("from Client").list();
}
public void save(Client client) {
sessionFactory.getCurrentSession().save(client);
}
public void update(Client client) {
// TODO Auto-generated method stub
}
public void remove(Client client) {
// TODO Auto-generated method stub
}
}
And lastly my hibernate.cfg:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="ee.st.running.model.Client" />
<mapping class="ee.st.running.model.Order" />
</session-factory>
</hibernate-configuration>
I modified it several times, adding some additional info. What I currently want is to check, whether it works, so in the Main class I wrote primitive code to store info to database and see whether it actually stored, so I could move on:
package ee.st.running.aktorstask;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import ee.st.running.dao.*;
import ee.st.running.model.*;
public class Main {
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext ("./config.xml");
Client clientx = (Client) appContext.getBean("client");
Client client = new Client ();
client.setName("Vasilij");
client.setIdCode(389844455);
client.setAddress("Pae 485 54 Tartu");
client.setSurename("B");
//client.makeorder();
clientx.save(client);
}
}
It now gives me mappingexception
Any ideas, why? And, by the way who is "AnnotationConfiguration instance" and where it supposed to be?
Normal hibernate.cfg.xml uses Configuration class for building Sessionfactory object
return new Configuration().configure().buildSessionFactory();
You need to use AnnotationConfiguration for the same.
In your above example you have specified classes in sessionFactory bean as
<property name="annotatedClasses">
<list>
<value>ee.st.running.model.Client</value>
<value>ee.st.running.dao.ClientDAOImpl</value>
<value>ee.st.running.model.Order</value>
<value>ee.st.running.dao.OrderDAOImpl</value>
</list>
</property>
Wrong thing you did here is you added DAO classes also. AnnotatedClasses should be domain classes.
You can remove them and keep only Client and Order in that.
Secondly you have also provided hibernate.cfg.xml file. Hence you can remove that as you are using annotated classes.
Hence final code may look like this:
<property name="annotatedClasses">
<list>
<value>ee.st.running.model.Client</value>
<value>ee.st.running.model.Order</value>
</list>
</property>
And removing hibernate.cfg.xml

org.hibernate.hql.ast.QuerySyntaxException: UserType is not mapped [from UserType]

The exception is about table not mapping to class, however I failed to debug what went wrong.
I have checked the xml configurations. the class is UserType and the database table is called UserType as well.
UserType.java:
package com.howtodoinjava.entity;
public class UserType {
private int _userTypeID;
private String _userTypeName;
private boolean _typeIsSuperUser;
public int getUserTypeID() { return _userTypeID; }
public String getUserTypeName() {return _userTypeName; }
public boolean getTypeIsSuperUser() {return _typeIsSuperUser; }
public UserType setUserTypeID(int id) { _userTypeID = id; return this; }
public UserType setUserTypeName(String name) { _userTypeName = name; return this; }
public UserType setTypeIsSuperUser(boolean isSuperUser) { _typeIsSuperUser = isSuperUser; return this; }
}
UserTypeDAOImpl.java:
package com.howtodoinjava.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.howtodoinjava.entity.UserType;
#Repository
public class UserTypeDAOImpl implements UserTypeDAO {
#Autowired
private SessionFactory sessionFactory;
public void add(UserType ut) {
this.sessionFactory.getCurrentSession().save(ut);
}
#SuppressWarnings("unchecked")
public List<UserType> getAll() {
return this.sessionFactory.getCurrentSession().createQuery("from UserType").list();
}
public void delete(Integer id) {
UserType ut= (UserType) sessionFactory.getCurrentSession().load(
UserType.class, id);
if (null != ut) {
this.sessionFactory.getCurrentSession().delete(ut);
}
}
}
EditUserTypeController.java:
#Controller
public class EditUserTypeController{
#Autowired
private UserTypeManager userTypeManager;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String list(ModelMap map)
{
map.addAttribute("UserType", new UserType());
map.addAttribute("UserTypeList", userTypeManager.getAll());
return "editEUserTypeList";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUserType(#ModelAttribute(value="ut") UserType ut, BindingResult result)
{
userTypeManager.add(ut);
return "redirect:/";
}
#RequestMapping("/delete/{id}")
public String deleteUserType(#PathVariable("id") Integer id)
{
userTypeManager.delete(id);
return "redirect:/";
}
public void setUserTypeManager(UserTypeManager new_utm) {
this.userTypeManager = new_utm;
}
}
my UserType-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<context:annotation-config />
<context:component-scan base-package="com.howtodoinjava.controller" />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="UserTypeDAO" class="com.howtodoinjava.dao.UserTypeDAOImpl"></bean>
<bean id="UserTypeManager" class="com.howtodoinjava.service.UserTypeManagerImpl"> </bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
hibernate.cfg.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping resource="UserType.hbm.xml" />
</session-factory>
</hibernate-configuration>
UserType.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.howtodoinjava.entity.UserType" table="UserType">
<meta attribute="class-description">
user type
</meta>
<id name="_userTypeID" column="UserTypeId" type="int"> <generator class="native"/> </id>
<property name="_userTypeName" column="UserTypeName" type="string"/>
<property name="_typeIsSuperUser" column="TypeIsSuperUser" type="string"/>
</class>
</hibernate-mapping>
I appreciate any helps!
The problem is in hibernate mapping configuration:
name: should be same as class field name and
column: is the name of database table column, or the column name to be set while table creation by hibernate.
Note: The mapping file instructs Hibernate how to map the defined class to the database table.
your UserType.hbm.xml should be look like:
<hibernate-mapping>
<class name="com.howtodoinjava.entity.UserType" table="UserType">
<meta attribute="class-description">
user type
</meta>
<id name="_userTypeID" column="userTypeID" type="int">
<generator class="native"/>
</id>
<property name="_userTypeName" column="userTypeName" type="string"/>
<property name="_typeIsSuperUser" column="typeIsSuperUser" type="string"/>
</class>
</hibernate-mapping>
It turned out this is related to the HQL issue: instead of using from UserType, use from com.howtodojava.entity.UserType;
and the error message will be gone.

Categories