Hibernate Bean Creating Exception - java

I am using Spring-ORM to add a Employee* object in Table called emp using HibernateTemplate.
But when I'm trying to execute the program I'm getting this error:
Error creating bean with name 'testBean': Unsatisfied dependency expressed through field 'dao'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:E rror creating bean with name 'empDaoImpl': Unsatisfied dependency expressed through field 'ht'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ht' defined in class path resource [applicationContext.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is 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.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [alter table emp add empno number(10,0) not null]
This is My java bean
#Service
public class TestBean
{
#Autowired
private EmpDao dao;
public void persistEmp(int empid,String empName,int sal,int deptno)
{
Employee e=new Employee();
e.setEmpid(empid);
e.setEmpName(empName);
e.setEmpSalary(sal);
e.setDeptNum(deptno);
dao.save(e);
}
public void updateEmp(int empid,String empName,int sal,int deptno)
{
Employee e=new Employee();
e.setEmpid(empid);
e.setEmpName(empName);
e.setEmpSalary(sal);
e.setDeptNum(deptno);
dao.update(e);
}
public void deleteEmp(int empid)
{
dao.deleteEmployee(empid);
}
public void selectEmps()
{
List lt=dao.selectEmployees();
Iterator it=lt.iterator();
while(it.hasNext())
{
Employee e1=(Employee)it.next();
System.out.println(e1);
}
}
}
*This is my Entity class
#Entity
#Table(name="emp")
public class Employee
{
#Id
#Column(name="empno")
private int empid;
#Column(name="ename")
private String empName;
#Column(name="sal")
private int empSalary;
#Column(name="deptno")
private int deptNum;
//Setters and Getters
public String toString()
{
return "Employee["+empid+" "+empName+" "+empSalary+" "+deptNum+"]";
}
}
This is my EmpDaoImpl class
#Repository
#Transactional
public class EmpDaoImpl implements EmpDao
{
#Autowired
private HibernateTemplate ht;
public void deleteEmployee(int empid)
{
Employee e=(Employee)ht.get(Employee.class, empid);
ht.delete(e);
System.out.println("one Employee object is deleted");
}
public List selectEmployees()
{
List empList=ht.find("from Employee e");
return empList;
}
public void save(Employee e)
{
ht.save(e);
System.out.println("Object is saved ");
}
public void update(Employee e)
{
ht.update(e);
System.out.println("Object is Updated");
}
}
This is my Main class
public class Main
{
public static void main(String[] args)
{
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
TestBean testB=(TestBean)ctx.getBean("testBean");
testB.persistEmp(7999, "naveen", 55555, 40);
System.out.println("===============================");
}
}
This is my applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.pack1"></context:component-scan>
<bean id="ht" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="ds"></property>
<property name="annotatedClasses">
<list>
<value>com.pack1.entity.Employee</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
</value>
</property>
</bean>
<bean id="txm" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe"/>
<property name="username" value="system"/>
<property name="password" value="tiger"/>
</bean>
<tx:annotation-driven transaction-manager="txm"/>
</beans>

When hibernate.hbm2ddl.auto is set to update Hibernate won't modify existing table column definitions. So, you can manually alter the column definition or drop the table/column and run your code. In the latter case, hibernate will create the column if it is not present.
Please refer here, here and here for more info on hibernate.hbm2ddl.auto options and how they work.

Related

Spring MVC and Spring Data Repository doesnt work

I am trying to make a simple Spring MVC application using Spring Data, hibernate and H2 database. But spring cannot find the repository as a bean.
The error when application start:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'taskService': Unsatisfied dependency expressed through method 'setTaskRepository' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.spring.intership.repositories.TaskRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.spring.intership.repositories.TaskRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
TaskRepository.java
#Repository
public interface TaskRepository extends JpaRepository<Task, Long> {
}
TaskSerice.java
public interface TaskService {
public List<Task> getAll();
public void save(Task t);
}
TaskServiceImpl.java
public class TaskServiceImpl implements TaskService {
private TaskRepository taskRepository;
#Override
public void add(Task task) {
taskRepository.save(task);
}
#Override
public List<Task> getAll() {
LinkedList<Task> tasks = new LinkedList<>();
taskRepository.findAll().forEach(tasks::add);
return tasks;
}
#Autowired
public void setTaskRepository(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
}
BeanConfiguration.java
#Configuration
public class BeanConfiguration {
#Bean
MemoryService memoryService() {
return new MemoryServiceImpl();
}
#Bean
TimeService timeService() {
return new TimeServiceImpl();
}
#Bean
NameService nameService() {
return new NameServiceImpl();
}
#Bean
TaskService taskService() {return new TaskServiceImpl(); }
}
application-context.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:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.jdbc.datasource.SimpleDriverDataSource" id="dataSource">
<property name="driverClass" value="${db.driverClass}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.spring.intership.entities" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.driver_class">org.h2.Drive</prop>
</props>
</property>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer"
init-method="start" destroy-method="stop">
<constructor-arg value="-web,-webAllowOthers,-webDaemon,-webPort,8082" />
</bean>
<jpa:repositories base-package="com.spring.intership.repositories"/>
</beans>
And i have this in my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
WEB-INF/config/application-context.xml
WEB-INF/config/application.properties
</param-value>
</context-param>
I have very little experience in MVC spring (a little more in boot) so please consider the most obvious mistakes too;
P.S. My Task.java
#Entity
#Transactional
public class Task {
private long number;
private String description;
private Date date;
#Id
#Column(name = "ID")
public long getNumber()
{
return number;
}
#Basic
#Column(name = "DESCRIPTION")
public String getDescription()
{
return description;
}
#Basic
#Column(name = "DATE")
public Date getDate()
{
return date;
}
public void setNumber(long number)
{
this.number = number;
}
public void setDate(Date date) {
this.date = date;
}
public void setDescription(String description) {
this.description = description;
}
}
try this tips:
Use "#ComponentScan" annotation in "BeanConfiguration" class. Note that you can use "#ComponentScan(basePackages = "com.example.package")" to force scan of the package when your repositories are.
You can use "#EnableJpaRepository(basePackages = "package.of.repositories")" to scan specific package to find ONLY repositories.
Let's check if "Task" class is annoted with "#Entity"
Consider to convert you context to class and try to use annotation instead of xml bean definition.
If you choose to use #ComponentScan annotation consider to scan all packages' tree. If your packages are "com.example.repository", "com.example.controller", "com.example.service" let's scan "com.example" in order to scan also future packages' you will add
I agree with #Luke.
Also you should autowire TaskRepository in TaskService.
public class TaskServiceImpl implements TaskService {
#Autowired
private TaskRepository taskRepository;
....

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean

I am creating a ShoppingCart App using Spring-mvc.In dao layer I am using Spring-Hibernate ORM feature.
#Repository("baseDao")
public class BaseDaoImpl<T extends ShoppingCartEntity> implements BaseDao<T>
{
#Autowired
protected SessionFactory sessionFactory;
private Class<T> entityClass;
public BaseDaoImpl(Class<T> entityClass) {
super();
this.entityClass = entityClass;
}
public Serializable save(T entity) {
return sessionFactory.getCurrentSession().save(entity);
}
public void update(T entity) {
sessionFactory.getCurrentSession().update(entity);
}
public void saveOrUpdate(T entity) {
sessionFactory.getCurrentSession().saveOrUpdate(entity);
}
}
CartDaoImpl.java
#Repository("cartDao")
public class CartDaoImpl extends BaseDaoImpl<CartMaster> implements CartDao {
private Class<CartMaster> entityClass;
public CartDaoImpl(#Value("com.orgn.shc.entity.CartMaster")Class<CartMaster> entityClass) {
super(entityClass);
this.entityClass = entityClass;
}
//other getter & setter
}
I have a base entity class named ShoppingCartEntity.java.
#MappedSuperclass
public class ShoppingCartEntity implements Serializable {
private static final long serialVersionUID = 1L;
//other fields
}
CartMaster.java:
#Entity
#Table(name = "SHOP_CART_MASTER")
public class CartMaster extends ShoppingCartEntity {
//other fields
}
Now,during deployment of application in weblogic I am getting following exception:
<28 Dec, 2017, 11:48:08,916 PM IST> <Error>
<org.springframework.web.servlet.DispatcherServlet> <BEA-000000> <Context
initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name 'baseDao' defined in URL [zip:C:/Oracle
/Middleware/ORACLE_HOME/user_projects/domains/wl_server/servers
/AdminServer/tmp/_WL_user/shoppingcart/8i2b70/war/WEB-INF/lib
/wl_cls_gen.jar!/com/orgn/shc/dao/impl/BaseDaoImpl.class]: Unsatisfied
dependency expressed through constructor parameter 0; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type 'java.lang.Class<?>' available: expected at least
1 bean which qualifies as autowire candidate. Dependency annotations: {}
at
org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
Its spring-bean configuraation part as below
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/SHPDS"
expected-type="javax.sql.DataSource" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.orgn.shc.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
</props>
</property>
</bean>
<mvc:annotation-driven />
<context:component-scan base-package="com.orgn.shc" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:resources mapping="/assets/**" location="/assets/" />
My perception is that #Value annotation at constructor level is sufficient to inject the dependencies accordingly in sub classes.
Can anyone has any suitable solution to this?
Remove #Repository("baseDao") from your BaseDaoImpl as it should not be created as a separate bean; instead, it should be only used as a parent for other DAO classes. I would also make it abstract and its constructor protected to avoid accidental instantiation.
Also, it looks like you need to change the constructor of your CartDaoImpl to the following:
public CartDaoImpl() {
super(CartMaster.class);
}
And I don't believe you actually need entityClass field in CartDaoImpl as you know the class of your entity in this DAO: it's CartMaster.class. At the same time, in BaseDaoImpl that entityClass field may be useful to read entities from database (even though you don't have such methods).

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.

Issue while autowiring strongly typed collections

I am using spring 3.2.2. I am facing issue while autowring the collection by spring's byType autowiring mode. I have created the below example.
Bean defination:
package com.springaction.testmultidimesionalcollection;
import java.util.ArrayList;
/**
* #author jinesh
*
*/
public class Address {
ArrayList<Country> country;
public ArrayList<Country> getCountry() {
return country;
}
/**
* #param country the country to set
*/
public void setCountry(ArrayList<Country> country) {
this.country = country;
}
}
Below is the spring configuration file testmultidimensionalcollection.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="addressMiddleEast" class="com.springaction.testmultidimesionalcollection.Address" autowire="byType">
</bean>
<bean id="countryChina" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="China" />
</bean>
<bean id="countryIndia" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="India" />
</bean>
<bean id="countryAus" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="Australia" />
</bean>
<bean id="middeastcountryQuatar" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="Quatar" />
</bean>
<bean id="middeastcountryIsrael" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="Israel" />
</bean>
<bean id="middeastcountryYemen" class="com.springaction.testmultidimesionalcollection.Country">
<property name="countryName" value="Yemen" />
</bean>
</beans>
Here I have strong type collection in the Address class. So all the elements of the country are supposed to be added inside the Country properties arraylist but when I am executing the below code I am getting the Null pointer exception.
package com.springaction.testmultidimesionalcollection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* #author jinesh
*
*/
public class TestMultiDimensionalMain {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("com/springaction/testmultidimesionalcollection/testmultidimensionalcollection.xml");
Address addrs=(Address)context.getBean("addressMiddleEast");
System.out.println("address size:" + addrs.getCountry().size());
}
}
I am not able to understand, why spring is not able to automatically detect the country beans and add them to the array list property of address bean? Have I missed something in the configuration?
You haven't actually requested that anything be autowired. This bean
<bean id="addressMiddleEast" class="com.springaction.testmultidimesionalcollection.Address" autowire="byType">
</bean>
and class
public class Address {
ArrayList<Country> country;
public ArrayList<Country> getCountry() {
return country;
}
/**
* #param country the country to set
*/
public void setCountry(ArrayList<Country> country) {
this.country = country;
}
}
simply has property setters/getters. You need to use #Autowired (or the related annotations).
public class Address {
#Autowired
ArrayList<Country> country;
If you can't use #Autowired (why not???), you would need to create a bean of type List that has a reference to each of your Country beans, like in (now deleted) tichodrama's answer.
This is explained in the Spring IoC documentation here

Categories