hibernate persistence does not create tables - spring

I'm using below maven dependencies in my spring mvc project:
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<!-- hibernate -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901.jdbc4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.16.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
and here is my persistence.xml
<?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_1_0.xsd" version="1.0">
<persistence-unit name="PersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.sepehrgh.domain.entity.UploadEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost/test_jpa" />
<property name="hibernate.connection.useUnicode" value="true" />
<property name="hibernate.connection.characterEncoding" value="UTF-8" />
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.connection.username" value="postgres" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
UploadEntity:
#Entity
#Table(name = "uploads", schema = "public")
public class UploadEntity {
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column
private long id;
#Column
private String title;
#Column(columnDefinition = "text")
private String description;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
When I run project. I get following error, so no table get created:
201
6-05-30 21:07:38 ERROR SchemaExport:425 - HHH000389: Unsuccessful: create table public.uploads (id bigserial not null, description text, title varchar(255), primary key (id))
2016-05-30 21:07:38 ERROR SchemaExport:426 - type not found or user lacks privilege: BIGSERIAL
And its totally strange because I'm using same codes and logic in another older project and its totally working! Am I missing something ?
Also you might need to know that persistence.xml is under META-INF in directory marked as resources. same place it is in all my other working projects! any idea?
FYI: when I run this query " create table public.uploads (id bigserial not null, description text, title varchar(255), primary key (id)) " in postgresql server, it works just fine! my postgresql version is 9.4, and Im running my project in Intellij Idea with TomEE web-profile 1.7

In a EE server JPA uses non-jta-datasource for RESOURCE_LOCAL persistence-unit.
Either configure the datasource in resources.xml/tomee.xml or set in conf/system.properties: openejb.guess.resource-local-datasource-properties-configured=true

Related

How to fix "Failed to obtain JDBC Connection" in spring jdbc

I'm new using Spring jdbc and I'm having an error connecting it to
MySQL Database, I already read all tutorials but still haven't found
the problem.
** Following Error occurred **
My Program started....... Exception in thread "main" org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to
obtain JDBC Connection; nested exception is
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Could not create connection to database server. at
org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:82)
at
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:612)
at
org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:862)
at
org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:917)
at
org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:927)
at com.spring.jdbc.App.main(App.java:24) Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:
Could not create connection to database server. at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method) at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at
com.mysql.jdbc.Util.getInstance(Util.java:384) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:973) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918) at
com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2588)
at
com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2321)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:832) at
com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:46) at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native
Method) at
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
at
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at
com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417) at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344)
at
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:681)
at
java.sql/java.sql.DriverManager.getConnection(DriverManager.java:190)
at
org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:154)
at
org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:145)
at
org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205)
at
org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169)
at
org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:158)
at
org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:116)
at
org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79)
... 5 more Caused by: java.lang.NullPointerException: Cannot invoke
"java.util.Map.get(Object)" because "this.serverVariables" is null at
com.mysql.jdbc.ConnectionImpl.getServerCharacterEncoding(ConnectionImpl.java:3307)
at com.mysql.jdbc.MysqlIO.sendConnectionAttributes(MysqlIO.java:1985)
at
com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1911)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1288) at
com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2506)
at
com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2539)
... 25 more
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>com.spring.jdbc</groupId>
<artifactId>springjdbc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springjdbc</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
config.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"
xmlns:p="http://www.springframework.org/schema/p"
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">
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" name="ds">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/springjdbc"/>
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean class="org.springframework.jdbc.core.JdbcTemplate" name="template" >
<property name="dataSource">
<ref bean="ds" />
</property>
</bean>
</beans>
App.java
package com.spring.jdbc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "My Program started......." );
// spring jdbc => JdbcTemplate
ApplicationContext context = new ClassPathXmlApplicationContext("com/spring/jdbc/config.xml");
JdbcTemplate template = context.getBean("template",JdbcTemplate.class);
//Insert Query
String query = "insert into student(id,name,city) values(?,?,?)";
//fire Query
int result = template.update(query,456,"Pooja Joshi","Pune");
System.out.println("number of records inserted.."+ result);
}
}
Student.java
package com.spring.jdbc;
public class Student {
private int id;
private String name;
private String city;
public Student() {
// TODO Auto-generated constructor stub
}
public Student(int id, String name, String city) {
super();
this.id = id;
this.name = name;
this.city = city;
}
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 String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", city=" + city + "]";
}
}

Invocation of init method failed; nested exception is javax.persistence.PersistenceException

Guys i've came across a problem which i googled a lot and tried to find solutions in stackflow,however it failed and there seems no body have met with the same problem .What's more , i've got exhausted.Below is my code and configuration files.
<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>com.robot</groupId>
<artifactId>springdata</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-
data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/hibernate/hibernate-entitymanager --
>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
</dependencies>
</project>
in my dependency xml,i add spring data and hibernate.
<?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:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--1 配置数据源-->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="url" value="jdbc:mysql:///spring_data"></property>
</bean>
<!--2 配置EntityManagerFactory-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.robot"/>
<property name="jpaProperties">
<props>
<prop
key="hibernate.ejb.naming_strategy">
org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!--<!–3 配置事务管理器–>-->
<!--<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">-->
<!--<property name="entityManagerFactory" ref="entityManagerFactory"/>--
>
<!--</bean>-->
<!--<!–4 配置支持注解的事务–>-->
<!--<tx:annotation-driven transaction-manager="transactionManager"/>-->
<!--<!–5 配置spring data–>-->
<!--<jpa:repositories base-package="com.robot" entity-manager-factory-
ref="entityManagerFactory"/>-->
<!--<context:component-scan base-package="com.robot"/>-->
</beans>
below is my entity class, it is very simple,so i don't think any thing will go wrong.
package com.robot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Employee {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
#GeneratedValue
#Id
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
below is my test class
package com.robot.dao;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StudentSpringDataTest {
private ApplicationContext ctx=null;
#Before
public void setUp(){
System.out.println("Set Up");
ctx= new ClassPathXmlApplicationContext("beans_new.xml");
}
#After
public void tearDown(){
System.out.println("Tear Down");
ctx =null;
}
#Test
public void initializationTest(){
}
}
when i run the initializationTest method it show error like the picture described.
log info
For your next questions do not include your stack traces as image.
The error is clear: "No identifier specified for entity: ....", and that is because you have your #Id annotation on a set method, and you can not use annotation on settters. You need to use it either on the field or on the getter method.
Hibernate mapping annotations - Access type
Try:
#Entity
public class Employee {
#GeneratedValue
#Id
private int id;
...
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
...
}

Spring + MVC + Hibernate: Can't read my requestBody

and again a question converning Sring, MVC and Hibernate. I tried every possible solution given here. But nothing fixed my problem.
What I want to do:
Add a new entry into my SQl Database by sending a PUT-Request to my Server with a JSON Object.
What works:
My server is working, all GET Request do what they are supposed to.
Also my database recognizes and adds a new entry, HOWEVER all attributes are NULL
My setup:
Database: SQL (generated with XAMPP)
Server: Spring, MVC, Hibernate
Here are my files (please note that I already inluded the JacksonMapper)
applicationContext-servlet.xml
<context:component-scan base-package="ma" />
<mvc:annotation-driven />
<tx:annotation-driven />
<!-- Hibernate Integration -->
<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/travelpal" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="ma" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
<!-- Added to support JSON PUT -->
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prefixJson" value="false" />
<property name="supportedMediaTypes" value="application/json" />
</bean>
I tried to add this part as it appeared in a lot of answers, but Spring doesn't allow me to add it. It always displays an error, stating "Build path is incomplete. Cannot find class file for javax/servlet/ServletException"
<bean id="annotationHandlerAdapter"
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="order" value="1" />
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
<property name="supportedMediaTypes" value="application/json"/>
</bean>
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</list>
</property>
My pom.xml
<dependencies>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<!-- Hibernate Integration START -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.9.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- Testint added -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.8</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>TravelPalServer</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>applicationContext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>applicationContext</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Added for JSON PUT -->
<filter>
<filter-name>httpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>httpMethodFilter</filter-name>
<servlet-name>applicationContext</servlet-name>
</filter-mapping>
My PalDAO (excerpt)
#Override
public void insertPal(Pal pal) {
System.out.println("Inserting Pal: " + pal.getName());
sessionFactory.getCurrentSession().save(pal);
}
pal.getName() returns NULL
The PalController
#RequestMapping(value="/", method = RequestMethod.PUT)
public #ResponseBody Pal insertPal(#ModelAttribute Pal person) {
System.out.println("Im Controller; adding Pal: " + person.getName());
palService.insertPal(person);
return person;
}
Here I also tried #RequestBody, however then the response says: "... response was syntactically incorrect"
Also, the person.getName() returns NULL
Pal.java
#Entity
#Table(name="Pal")
public class Pal {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="ID", nullable = false)
private Long id;
#Column(name="name", nullable = true)
private String name;
#Column(name="age", nullable = false)
private int age;
#Column(name="gender", nullable = false)
private String gender;
#ManyToOne
#JoinColumn(name="locationId")
private Location locationId;
#ManyToOne
#JoinColumn(name="settingId")
private Settings settingId;
public Pal() {}
public Pal(Long id, String name, String gender, Location locationId, Settings setting) {
super();
this.id = id;
this.name = name;
this.gender = gender;
this.locationId = locationId;
this.settingId = setting;
}
public Pal(Long id, String name, int alter) {
super();
this.id = id;
this.name = name;
this.age = alter;
}
public Pal(String name, int alter) {
super();
this.name = name;
this.age = alter;
}
public Pal(String name, int age, String gender) {
super();
this.name = name;
this.age = age;
this.gender = gender;
}
public Pal(Long id, String name, int age, Location locationId) {
super();
this.id = id;
this.name = name;
this.age = age;
this.locationId = locationId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Location getPosition() {
return locationId;
}
public void setPosition(Location locationId) {
this.locationId = locationId;
}
public Settings getSetting() {
return settingId;
}
public void setSetting(Settings setting) {
this.settingId = setting;
}
public Location getLocationId() {
return locationId;
}
public void setLocationId(Location locationId) {
this.locationId = locationId;
}
I really do hope someone can help me with this. I'm more than frustrated now.
EDIT
I send my request with RestClient (Firefox Addon)
URL : localhost:8080/TravelPalServer/pal/
And RequestBody is:
{
"name": "Elena",
"age": 22,
"gender": "Female"
}
I also tried not putting the "" around the attribute identifiers; doesn't change a thing
When I send the request from my iOS app (within the emulator) I get the same server response (so RestClient is not the problem)
That what appears in the console, after I send the PUT-Request
Hibernate: insert into Pal (age, gender, locationId, name, nationalityId, settingId) values (?, ?, ?, ?, ?, ?)
I think you need to do the following:
a) Specify a name for your #ModelAttribute
public #ResponseBody Pal insertPal(#ModelAttribute("person") Pal person) {
b) You need to submit the form using MIME type application/x-www-form-urlencoded. For example:
person=<json-string-here>

Understanding how nested Spring #Transactional works

I'm porting an EJB application to Spring and I'm facing some issues.
The application is running in standalone (that's why we choose spring) with eclipselink.
In this application I need to create an Order, for which I first need to create a Customer, the OrderLines and then add a Payment for this Order.
The problem is that I want to do all the insertion in a single Transaction so that if the payment fails to be persisted nothing must be persisted. I tried to achieve this but it looks like I'm spanning multiple independent transaction because in case of failure data are persisted to th DB (ex: payment fails, customer is created anyway).
Here is the entry point :
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
BeanFactory beanFactory = (BeanFactory) context;
MyService service = beanFactory.getBean(MyService.class);
service.getNewOrders(true);
}
Here is the bean I'm resolving (using beanFactory.getBean) :
#Component
#Scope("prototype")
public class MyService {
#Autowired
private CustomerService customerService;
#Autowired
private OrderService orderService;
#Autowired
private PaymentService paymentService;
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public void getNewOrders(boolean formattedOutput) {
try {
List<RawData> rawData = // Acquire data from a remote web service (http rest based)
for (RawData data : rawData) {
try {
this.handleOrder(data);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
private Order handleOrder(RawData rawData) throws Exception {
Customer customer = new Customer();
// Fill customer with rawData
this.customerService.create(customer);
Order order = new Order();
order.setCustomer(customer);
// Fill order with rawData
this.orderService.create(order);
Payment payment = new Payment();
payment.setOrder(order);
// Fill payment with rawData
this.paymentService.create(payment);
return order;
}
}
Each service looks like the following :
#Service
#Transactional
public class CustomerService {
#Autowired
private CustomerDao customerDao;
public void create(Customer customer) {
// some works on customer fields (checking values etc)
this.customerDao.create(customer);
}
}
Which are all backed by a Dao :
#Repository
public class CustomerDao {
#PersistenceContext
protected EntityManager em;
public void create(Customer customer) {
this.em.persist(customer);
}
}
Here are a few dependencies from maven pom.xml :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp</artifactId>
<version>0.8.0-rc1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.3.2</version>
</dependency>
Here is the persistence.xml :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/db" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
</properties>
</persistence-unit>
</persistence>
The spring configuration is the following :
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="myDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false" />
</map>
</property>
</bean>
<bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>
<tx:annotation-driven transaction-manager="myTxManager" />
<context:component-scan base-package="com.application" />
</beans>
EDIT
Added the creation of the ApplicationContext from the main, and an omitted method from MyService.java
How can you call the service method since it's private? It should be public. Private methods can't be intercepted by the Spring transactional interceptor, and can't be overridden by the CGLib dynamic proxy.
EDIT: OK, it's the usual problem. You're calling, from the main method, the method getNewOrders(), which is public and transactional. The Spring interceptor intercepts this method call. Since there is no transaction and the method is marked as SUPPORTS, Spring doesn't start any transaction.
Then this method calls the private handleOrder() method. Note that not only the method is private, which makes it impossible for Spring to intercept the method call, but the call is from a method in a component to a method in the same component. So even is the method was public, Spring could not intercept this method call. The transactional handling is proxy-based:
method --> transactional proxy --> Spring bean 1 --> transactional proxy --> Spring bean2
In this case, since you're not calling a method of another component, there is no proxy interception, and no transaction is started.
method --> transactional proxy --> Spring bean 1 --> transactional proxy --> Spring bean2
^ |
|___|
So, what you have to do is
create another Spring bean 'OrderHandler, for example)
move the handleOrder() method to this Spring bean, make it public
inject OrderHandler in MyService
And it will work fine.
This is explained in details in the Spring documentation.

MongoTemplate instance is not created inside spring

I want to try spring integration with MongoDB, For this purpose I did following things. but its not working Some how MongoTemplate instance is not created and throws java.lang.NullPointerException.
here is my 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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Activate annotation configured components -->
<context:annotation-config/>
<!-- Scan components for annotations within the configured package -->
<context:component-scan base-package="com.jeroenreijn.mongodb.example">
<context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
</context:component-scan>
<!-- Factory bean that creates the Mongo instance -->
<bean id="mongo" class="com.mongodb.Mongo">
<constructor-arg name="host" value="127.0.0.1" />
<constructor-arg name="port" value="27017" />
</bean>
<!-- Define the MongoTemplate which handles connectivity with MongoDB -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate" depends-on="mongo">
<constructor-arg name="mongo" ref="mongo"/>
<constructor-arg name="databaseName" value="firstMongoDB"/>
</bean>
<!-- Use this post processor to translate any MongoExceptions thrown in #Repository annotated classes -->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
here is my main method :
public class MainApplication {
/**
* This is a variable used for Logging purpose, I have used slf4j.
*/
final Logger LOGGER = LoggerFactory.getLogger(MainApplication.class);
#Autowired
MongoTemplate mongoTemplate;
public void savePerson(Person p) {
mongoTemplate.save(p);
}
public static void main(String[] args) {
Person p = new PersonImpl("1", "Ayushya", "Devmurari");
MainApplication ma = new MainApplication();
ma.savePerson(p);
ma.LOGGER.info("Person named : " + p.getName() + " with id : "
+ p.getId() + " is saved.");
}
}
Here is my model class :
#Document(collection = "AnotherPersonCollection")
public class PersonImpl implements Person {
private String id;
private String name;
private String surname;
// Constructor
public PersonImpl() {
}
public PersonImpl(String id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
#Override
public String getId() {
return id;
}
#Override
public void setId(String id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
#Override
public String getSurname() {
return surname;
}
#Override
public void setSurname(String surname) {
this.surname = surname;
}
#Override
public String toString() {
return "Person has name " + "Id :" + id + "\n" + name + " \n"
+ "surname :" + surname;
}
}
Need assistance I have tried several tutorials, like mkyong and many others and I have faced NoBeanDefinitionFound for "mongoTemplate" error: so I tried this.
UPDATE: 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.discusit</groupId>
<artifactId>MongoDBAppTrail4</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>Trying to create MongoDBApp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- Log4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<!-- Spring framework -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.0</version>
</dependency>
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
</project>
Here is my stacktrace :
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:568)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1102)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:278)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)
at com.discusit.main.MainApplication.main(MainApplication.java:39)
I have look #Aayush solution. I have found two errors:
You don't call correctly your xml file configuration.
Before:
ApplicationContext ctx = new GenericXmlApplicationContext("classpath*:application-context.xml");
After:
ApplicationContext ctx = new GenericXmlApplicationContext("classpath:META-INF/applicationContext.xml");
You call an ExceptionTranslationPostProcessor. Why ? This call causes an error. I removed it.
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
So finally, i have tested your application with small changes and all it's working. Dont forget to start mongodb server and create your database "firstMongoDB". For more information read here: http://docs.mongodb.org/manual/tutorial/getting-started/
I have published your project in github: https://github.com/m-reka/spring-data-mongoTemplate
Tell me when i can remove it :)
As mentioned, you have to create application context in your main class. To use autowire you can define your main class as spring bean.
<?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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- your mongodb bean befinitions -->
<bean class="fullpackage.MainApplication"/>
</beans>
And then just get the instance in your main class
public class MainApplication {
/**
* This is a variable used for Logging purpose, I have used slf4j.
*/
final Logger LOGGER = LoggerFactory.getLogger(MainApplication.class);
#Autowired
MongoTemplate mongoTemplate;
public void savePerson(Person p) {
mongoTemplate.save(p);
}
public static void main(String[] args) {
ApplicationContext ctx = new GenericXmlApplicationContext("application-context.xml");
MainApplication ma = ctx.getBean(MainApplication.class);
Person p = new PersonImpl("1", "Ayushya", "Devmurari");
ma.savePerson(p);
ma.LOGGER.info("Person named : " + p.getName() + " with id : " + p.getId() + " is saved.");
}
}
in your main method add :
ApplicationContext context =
new ClassPathXmlApplicationContext("application-context.xml"); //change xml path as you need.
MMongoTemplate mongoTemplate=context.getBean(MMongoTemplate.class);
As you use main method, which is skipping loading the beans in spring context , so the autowire will not work.
use this way to configure mongodb
AppMongoConfig.class
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import com.mongodb.Mongo;
#Configuration
public class AppMongoConfig {
public #Bean
MongoDbFactory mongoDbFactory() throws Exception {
return new SimpleMongoDbFactory(new Mongo(), "testing");
}
public #Bean
MongoTemplate mongoTemplate() throws Exception {
//remove _class
MappingMongoConverter converter = new MappingMongoConverter(mongoDbFactory(), new MongoMappingContext());
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory(), converter);
return mongoTemplate;
}
}
/-------------------------------------------------------------------------------------------------/
testing-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.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.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
<bean
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<mongo:mongo host="testing" port="27017">
<mongo:options connections-per-host="100"
threads-allowed-to-block-for-connection-multiplier="5"
max-wait-time="120000000"
connect-timeout="10000000"
socket-keep-alive="true"
socket-timeout="15000000"
auto-connect-retry="true"/>
</mongo:mongo>
<mongo:db-factory dbname="testing"
mongo-ref="mongo" />
<bean id="mongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
<constructor-arg name="typeKey">
<null />
</constructor-arg>
</bean>
<bean id="mongoMappingContext"
class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" />
<bean id="mongoConverter"
class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mappingContext" ref="mongoMappingContext" />
<property name="typeMapper" ref="mongoTypeMapper"></property>
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="mongoConverter" />
<property name="writeResultChecking" value="EXCEPTION" />
</bean>
</beans>
/---------------------------------------------------------------------------/
#Autowired
private MongoTemplate mongoTemplate ;
#Override
public String methodTesting(classname object) { //classname change to your class name
String response="failer";
try {
if (!mongoTemplate.collectionExists(classname.class)) {
mongoTemplate.createCollection(classname.class);
}
mongoTemplate.save(object);
`response="success";`
} catch (Exception e) {
System.out.println("inside catch");
e.printStackTrace(); // TODO: handle exception
}
return response;
}

Resources