I have a simple spring jdbc program but when I run the program I get a queryTimeOut exception.
Here is the complete stackTrace
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/dao/QueryTimeoutException
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.<init>(SQLErrorCodeSQLExceptionTranslator.java:87)
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.<init>(SQLErrorCodeSQLExceptionTranslator.java:103)
at org.springframework.jdbc.support.JdbcAccessor.getExceptionTranslator(JdbcAccessor.java:99)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:407)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:519)
at com.test.spring.EmployeeDao.saveEmployee(EmployeeDao.java:14)
at com.test.spring.Test.main(Test.java:13)
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.QueryTimeoutException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 7 more
Table:
create table employee(emp_name varchar2(30),address varchar2(30),salery number(10),emp_id number(10));
Employee.java:
package com.test.spring;
public class Employee {
private String emp_name;
private String address;
private int salery;
private int emp_id;
public Employee()
{
}
public Employee(String emp_name,int emp_id)
{
this.emp_name=emp_name;
this.emp_id=emp_id;
}
public Employee(String emp_name,String address,int salery,int emp_id)
{
this.emp_name=emp_name;
this.address=address;
this.salery=salery;
this.emp_id=emp_id;
}
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getSalery() {
return salery;
}
public void setSalery(int salery) {
this.salery = salery;
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
}
EmployeeDao.java:
package com.test.spring;
import org.springframework.jdbc.core.JdbcTemplate;
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int saveEmployee(Employee e){
//String query="insert into employee (emp_name,address,salery,emp_id)values(?,?,?,?)";//not getting any exception
String query="insert into employee (emp_name,address,salery,emp_id)values("+e.getEmp_name()+","+e.getAddress()+","+e.getSalery()+","+e.getEmp_id()+")";//getting queryTimeOutException
return jdbcTemplate.update(query);
}
}
ApplicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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="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="mysql" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.test.spring.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
Test.java:
package com.test.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
int status=dao.saveEmployee(new Employee("Amit","Pingla",35000,102));
System.out.println(status);
}
}
The error points out that you're missing a class from your classpath. It doesn't mean that specific exception would get thrown during that particular invocation; but it simply doesn't find the class for it.
To add the QueryTimeoutException class in your classpath, you need to add a dependency on the spring-tx module.
You can add this dependency
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
If your are using maven or this one
[group: 'org.springframework', name: 'spring-tx', version: '4.1.6.RELEASE'],
if you are using gradle.
JdbcTemplate has queryTimeout property, you can try to configure it to a desired value.
Related
I am trying to use #Autowired Annotation in Spring for Dependency Injection
through a simple program but i give me following error
Exception in thread "main" java.lang.NullPointerException
at Customer.d(Customer.java:8)
at Main.main(Main.java:12)
Through xml configuration it give me correct result.
My xml file
<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-2.5.xsd">
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="person" class="Person">
<property name="name" value="khan"/>
</bean>
<bean id="cust" class="Customer"></bean>
</beans>
Customer Class
public class Customer {
#Autowired
private Person p;
public void display(){
System.out.println(p.getName());
}
}
Person Class
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
Main Class
public class Main {
public static void main(String[] a) {
Resource r=new ClassPathResource("SpringXml.xml");
BeanFactory factory=new XmlBeanFactory(r);
Customer c=(Customer)factory.getBean("cust");
c.display();
}
}
Try like this
public static void main(String[] args) throws Exception {
ApplicationContext context= new ClassPathXmlApplicationContext("SpringXml.xml");
Customer c = (Customer) context.getBean("cust");
c.display();
}
try this :
<bean id="person" class="com.yourpackage.Person">
<property name="name" value="khan"/>
</bean>
<bean id="cust" class="com.yourpackage.Customer">
<property name="p" ref="person"/>
</bean>
dont forget to add your fullpath class package
While Executing the program, I'm getting the particular error
**Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException:
Write operations are not allowed in read-only mode (FlushMode.MANUAL):
Turn your Session into FlushMode.
COMMIT/AUTO or remove 'readOnly' marker from transaction definition.**
every time. please someone help me. Here I am giving my codes which contains some error. In the Below code I have taken one employee data which will be stored in the employee table of MSSQL database. While working with only hibernate at that time i can able to persist my data. But, her i am unable to persist my data.
EmployeeHt.java
This is the entity class which is mapped to the employee table of MSSQL database
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="employee")
public class EmployeeHt {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Column(name="salary")
private int salary;
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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString() {
return "EmployeeHt [id=" + id + ", name=" + name + ", salary=" + salary + "]";
}
}
EmployeeHtDao.java
This is the class which contains hibernate template
import org.springframework.orm.hibernate5.HibernateTemplate;
public class EmployeeHtDao {
private HibernateTemplate ht;
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
public void saveEmployee(EmployeeHt e){
ht.save(e);
}
}
EmployeeHtTest.java
**This is the main class**
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class EmployeeHtTest {
private static ApplicationContext context;
public static void main(String[] args) {
context = new ClassPathXmlApplicationContext("hibernateTemplate.xml");
EmployeeHtDao dao=(EmployeeHtDao) context.getBean("edao");
EmployeeHt e=new EmployeeHt();
e.setId(104);
e.setName("Prangyan");
e.setSalary(30000);
dao.saveEmployee(e);
}
}
hibernateTemplate.xml
**This is the spring-xml file**
<?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="connpool" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=ananta"/>
<property name="username" value="sa"/>
<property name="password" value="pass123"/>
</bean>
<bean id="mysessionfactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="connpool"/>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
<property name="sessionFactory" ref="mysessionfactory"/>
</bean>
<bean id="edao" class="com.sdrc.hibernatetemplate.EmployeeHtDao">
<property name="ht" ref="hibernateTemplate"/>
</bean>
</beans>
Check for #Transactional annotation in you DAO.
It should be
#Transactional(readOnly = false)
I am trying to use Mongo Template with spring but it gives InvalidDataAccessApiUsageException
My Main Class is
package com.spring.mongodb.main;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.spring.mongodb.model.Person;
public class SpringDataMongoDBMain {
public static final String DB_NAME = "mydb";
public static final String PERSON_COLLECTION = "mycol";
public static final String MONGO_HOST = "localhost";
public static final int MONGO_PORT = 27017;
public static void main(String[] args) {
try{
Mongo mongo = new MongoClient(MONGO_HOST, MONGO_PORT);
System.out.println("Connected to MongoDB");
MongoOperations mongoOps = new MongoTemplate(mongo, DB_NAME);
System.out.println("Connected to database");
Person p = new Person("100", "ABC", "GRG PQR");
mongoOps.createCollection(PERSON_COLLECTION);
mongoOps.insert(p, PERSON_COLLECTION);
}catch(Exception e){
e.printStackTrace();
}
}
}
My Model Class is:
package com.spring.mongodb.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "person")
public class Person {
#Id
private String id;
private String name;
private String address;
public Person() {
}
public Person(String i, String n, String a) {
this.id = i;
this.name = n;
this.address = a;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public String toString() {
return id + "::" + name + "::" + address;
}
}
and my Spring.xml 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:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd">
<mongo:mongo host="localhost" port="27017" id="mongo" />
<mongo:db-factory dbname="mydb" mongo-ref="mongo"
id="mongoDbFactory" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<bean id="personDAO" class="com.journaldev.spring.mongodb.dao.PersonDAOImpl">
<constructor-arg name="mongoOps" ref="mongoTemplate" />
</bean>
</beans>
When I run the above code it gives following error :
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/dao/InvalidDataAccessApiUsageException
at com.spring.mongodb.main.SpringDataMongoDBMain.main(SpringDataMongoDBMain.java:21)
Caused by: java.lang.ClassNotFoundException: org.springframework.dao.InvalidDataAccessApiUsageException
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 1 more
I have added following jars:
mongodb-driver-3.1.1.jar
mongodb-driver-core-3.1.1.jar
spring-core-4.2.3.RELEASE.jar
spring-data-mongodb-1.6.1.RELEASE.jar
spring-data-commons-core-1.4.1.RELEASE.jar
I tried debuging the code it shows error when it comes to MongoOperations object creation and terminates.What I am doing wrong??
You're missing some jars (spring-tx, spring-beans, spring-context, spring-expression, etc..)
Have a look at maven to manage your dependencies
I am learning spring. while creating one example i got error.
The type ResultSetExtractor is not generic; it cannot be parameterized with arguments <List<Employee>>
I implement the app as below
Employee.java
package com.develop;
public class Employee {
private int id;
private String name;
private float salary;
public Employee(){}
public Employee(int id, String name, float salary){
this.id = id;
this.name = name;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
EmployeeDao.java
package com.develop;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
public class EmployeeDao {
private JdbcTemplate template;
public void setJdbcTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Employee> getAllEmployees(){
return template.query("select * from employee",new ResultSetExtractor<List<Employee>>(){
#Override
public List<Employee> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Employee> list=new ArrayList<Employee>();
while(rs.next()){
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
list.add(e);
}
return list;
}
});
}
}
Test.java
package com.develop;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
List<Employee> list=dao.getAllEmployees();
for(Employee e:list)
System.out.println(e);
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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="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="oracle" /> -->
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/springdatabase" />
<property name="username" value="root" />
<property name="password" value="admin123" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.develop.EmployeeDao">
<property name="template" ref="jdbcTemplate"></property>
</bean>
</beans>
Created Table
CREATE TABLE employee(id number(10),NAME varchar2(100),salary number(10));
The error message clearly sais it:
The ResultSetExtractor is not generic.
The interface was made generic in a newer version of Spring. But anyway, you can still use it's raw form, although you'd be forced you do a cast when working with the result of the extractData() method.
public List<Employee> getAllEmployees(){
return template.query("select * from employee",new ResultSetExtractor(){
#Override
public Object extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Employee> list=new ArrayList<Employee>();
while(rs.next()) {
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getInt(3));
list.add(e);
}
return list;
}
});
}
P.S.:
I assume you're using an old version of the Spring Framework, because in the newer version(s), the ResultSetExtractor is actually generic. So, you can either update your Spring version (but be careful, because this might cause you compilation problems and other issues), or stick to the approach used in the code snippet above.
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