Related
I am tying to test a simple spring mvc with angular 2 project running on eclipse.
The html page is getting displayed, but it is not loading any data from spring backend, any idea why this is happening?
console output:
Oct 06, 2017 11:31:22 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:AngularjsSpringRestExample' did not find a matching property.
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.47
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Sep 29 2017 13:46:41 UTC
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.47.0
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jdk1.8.0_111\jre
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_111-b14
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\dzhao\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Users\dzhao\Downloads\apache-tomcat-8.0.47
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\dzhao\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Users\dzhao\Downloads\apache-tomcat-8.0.47
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\dzhao\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Users\dzhao\Downloads\apache-tomcat-8.0.47\endorsed
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Oct 06, 2017 11:31:22 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_111\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_131/bin/server;C:/Program Files/Java/jre1.8.0_131/bin;C:/Program Files/Java/jre1.8.0_131/lib/amd64;C:\Program Files (x86)\GnuWin32\bin\;C:\Program Files (x86)\RBTools\bin;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Common Files\Microsoft Shared\Microsoft Online Services;C:\Program Files (x86)\Common Files\Microsoft Shared\Microsoft Online Services;C:\Program Files (x86)\IBM\RationalSDLC\common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\IBM\RationalSDLC\ClearCase\bin;C:\Program Files (x86)\IBM\gsk8\lib;C:\Program Files (x86)\IBM\gsk8\bin;C:\Program Files (x86)\IBM\RationalSDLC\ClearCase\RemoteClient\cteapis;C:\Program Files (x86)\Common Files\Check Point\UIFramework 3.0\Bin\;C:\Program Files (x86)\CheckPoint\Endpoint Security\Endpoint Common\bin;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\;C:\Users\dzhao\Java_Softwares\eclipse;;.
Oct 06, 2017 11:31:22 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Oct 06, 2017 11:31:22 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Oct 06, 2017 11:31:22 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Oct 06, 2017 11:31:22 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1209 ms
Oct 06, 2017 11:31:22 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Oct 06, 2017 11:31:22 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.47
Oct 06, 2017 11:31:25 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Oct 06, 2017 11:31:25 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 06, 2017 11:31:25 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'springrest'
Oct 06, 2017 11:31:25 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'springrest': initialization started
Oct 06, 2017 11:31:25 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'springrest-servlet': startup date [Fri Oct 06 11:31:25 EDT 2017]; root of context hierarchy
Oct 06, 2017 11:31:25 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/springrest-servlet.xml]
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/country/{id}],methods=[GET],produces=[application/json]}" onto public org.arpit.java2blog.bean.Country org.arpit.java2blog.controller.CountryController.getCountryById(int)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/countries],methods=[POST],produces=[application/json]}" onto public org.arpit.java2blog.bean.Country org.arpit.java2blog.controller.CountryController.addCountry(org.arpit.java2blog.bean.Country)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/countries],methods=[PUT],produces=[application/json]}" onto public org.arpit.java2blog.bean.Country org.arpit.java2blog.controller.CountryController.updateCountry(org.arpit.java2blog.bean.Country)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/country/{id}],methods=[DELETE],produces=[application/json]}" onto public void org.arpit.java2blog.controller.CountryController.deleteCountry(int)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/countries],methods=[GET],produces=[application/json]}" onto public java.util.List org.arpit.java2blog.controller.CountryController.getCountries()
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'springrest-servlet': startup date [Fri Oct 06 11:31:25 EDT 2017]; root of context hierarchy
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'springrest-servlet': startup date [Fri Oct 06 11:31:25 EDT 2017]; root of context hierarchy
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.handler.SimpleUrlHandlerMapping registerHandler
INFO: Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0'
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'springrest': initialization completed in 2531 ms
Oct 06, 2017 11:31:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Oct 06, 2017 11:31:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Oct 06, 2017 11:31:27 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 5321 ms
This 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.arpit.java2blog</groupId>
<artifactId>AngularjsSpringRestExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>AngularjsSpringRestExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<build>
<finalName>AngularjsSpringRestExample</finalName>
</build>
</project>
servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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 http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="org.arpit.java2blog.controller" />
<mvc:default-servlet-handler/>
</beans>
web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
controller class:
package org.arpit.java2blog.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class CountryController {
#Autowired
private HttpServletRequest request;
CountryService countryService = new CountryService();
#RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
public List getCountries() {
List listOfCountries = countryService.getAllCountries();
return listOfCountries;
}
#RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Country getCountryById(#PathVariable int id) {
return countryService.getCountry(id);
}
#RequestMapping(value = "/countries", method = RequestMethod.POST, headers = "Accept=application/json")
public Country addCountry(#RequestBody Country country) {
return countryService.addCountry(country);
}
#RequestMapping(value = "/countries", method = RequestMethod.PUT, headers = "Accept=application/json")
public Country updateCountry(#RequestBody Country country) {
return countryService.updateCountry(country);
}
#RequestMapping(value = "/country/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public void deleteCountry(#PathVariable("id") int id) {
countryService.deleteCountry(id);
}
}
bean class:
package org.arpit.java2blog.bean;
public class Country{
int id;
String countryName;
long population;
public Country() {
super();
}
public Country(int i, String countryName,long population) {
super();
this.id = i;
this.countryName = countryName;
this.population=population;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
}
service class:
package org.arpit.java2blog.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.arpit.java2blog.bean.Country;
/*
* It is just a helper class which should be replaced by database implementation.
* It is not very well written class, it is just used for demonstration.
*/
public class CountryService {
static HashMap<Integer,Country> countryIdMap=getCountryIdMap();
public CountryService() {
super();
if(countryIdMap==null)
{
countryIdMap=new HashMap<Integer,Country>();
// Creating some objects of Country while initializing
Country indiaCountry=new Country(1, "India",10000);
Country chinaCountry=new Country(4, "China",20000);
Country nepalCountry=new Country(3, "Nepal",8000);
Country bhutanCountry=new Country(2, "Bhutan",7000);
countryIdMap.put(1,indiaCountry);
countryIdMap.put(4,chinaCountry);
countryIdMap.put(3,nepalCountry);
countryIdMap.put(2,bhutanCountry);
}
}
public List getAllCountries()
{
List countries = new ArrayList(countryIdMap.values());
return countries;
}
public Country getCountry(int id)
{
Country country= countryIdMap.get(id);
return country;
}
public Country addCountry(Country country)
{
country.setId(getMaxId()+1);
countryIdMap.put(country.getId(), country);
return country;
}
public Country updateCountry(Country country)
{
if(country.getId()<=0)
return null;
countryIdMap.put(country.getId(), country);
return country;
}
public void deleteCountry(int id)
{
countryIdMap.remove(id);
}
public static HashMap<Integer, Country> getCountryIdMap() {
return countryIdMap;
}
// Utility method to get max id
public static int getMaxId()
{ int max=0;
for (int id:countryIdMap.keySet()) {
if(max<=id)
max=id;
}
return max;
}
}
html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<title>AngularJS $http Rest example</title>
<script type="text/javascript">
var app = angular.module("CountryManagement", []);
//Controller Part
app.controller("CountryController", function($scope, $http) {
$scope.countries = [];
$scope.countryForm = {
id : -1,
countryName : "",
population : ""
};
//Now load the data from server
_refreshCountryData();
//HTTP POST/PUT methods for add/edit country
// with the help of id, we are going to find out whether it is put or post operation
$scope.submitCountry = function() {
var method = "";
var url = "";
if ($scope.countryForm.id == -1) {
//Id is absent in form data, it is create new country operation
method = "POST";
url = '/AngularjsSpringRestExample/countries';
} else {
//Id is present in form data, it is edit country operation
method = "PUT";
url = '/AngularjsSpringRestExample/countries';
}
$http({
method : method,
url : url,
data : angular.toJson($scope.countryForm),
headers : {
'Content-Type' : 'application/json'
}
}).then( _success, _error );
};
//HTTP DELETE- delete country by Id
$scope.deleteCountry = function(country) {
$http({
method : 'DELETE',
url : '/AngularjsSpringRestExample/country/' + country.id
}).then(_success, _error);
};
// In case of edit, populate form fields and assign form.id with country id
$scope.editCountry = function(country) {
$scope.countryForm.countryName = country.countryName;
$scope.countryForm.population = country.population;
$scope.countryForm.id = country.id;
};
/* Private Methods */
//HTTP GET- get all countries collection
function _refreshCountryData() {
$http({
method : 'GET',
url : 'http://localhost:8080/AngularjsSpringRestExample/countries'
}).then(function successCallback(response) {
$scope.countries = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
function _success(response) {
_refreshCountryData();
_clearFormData()
}
function _error(response) {
console.log(response.statusText);
}
//Clear the form
function _clearFormData() {
$scope.countryForm.id = -1;
$scope.countryForm.countryName = "";
$scope.countryForm.population = "";
};
});
</script>
<style>
.blue-button{
background: #25A6E1;
filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
padding:3px 5px;
color:#fff;
font-family:'Helvetica Neue',sans-serif;
font-size:12px;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:4px;
border:1px solid #1A87B9
}
.red-button{
background: #CD5C5C;
padding:3px 5px;
color:#fff;
font-family:'Helvetica Neue',sans-serif;
font-size:12px;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:4px;
border:1px solid #CD5C5C
}
table {
font-family: "Helvetica Neue", Helvetica, sans-serif;
width: 50%;
}
caption {
text-align: left;
color: silver;
font-weight: bold;
text-transform: uppercase;
padding: 5px;
}
th {
background: SteelBlue;
color: white;
}
tbody tr:nth-child(even) {
background: WhiteSmoke;
}
tbody tr td:nth-child(2) {
text-align:center;
}
tbody tr td:nth-child(3),
tbody tr td:nth-child(4) {
text-align: center;
font-family: monospace;
}
tfoot {
background: SeaGreen;
color: white;
text-align: right;
}
tfoot tr th:last-child {
font-family: monospace;
}
td,th{
border: 1px solid gray;
width: 25%;
text-align: left;
padding: 5px 10px;
}
</style>
<head>
<body ng-app="CountryManagement" ng-controller="CountryController">
<h1>
AngularJS Restful web services example using $http
</h1>
<form ng-submit="submitCountry()">
<table>
<tr>
<th colspan="2">Add/Edit country</th>
</tr>
<tr>
<td>Country</td>
<td><input type="text" ng-model="countryForm.countryName" /></td>
</tr>
<tr>
<td>Population</td>
<td><input type="text" ng-model="countryForm.population" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" class="blue-button" /></td>
</tr>
</table>
</form>
<table>
<tr>
<th>CountryName</th>
<th>Population</th>
<th>Operations</th>
</tr>
<tr ng-repeat="country in countries">
<td> {{ country.countryName }}</td>
<td >{{ country.population }}</td>
<td><a ng-click="editCountry(country)" class="blue-button">Edit</a> | <a ng-click="deleteCountry(country)" class="red-button">Delete</a></td>
</tr>
</table>
</body>
</html>
If you want to return anything from a rest controller then you must use #ResponseBody annotation just before function declaration.
Like this in your case:
#RestController
public class CountryController {
#Autowired
private HttpServletRequest request;
CountryService countryService = new CountryService();
#RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseBody
public List getCountries() {
List listOfCountries = countryService.getAllCountries();
return listOfCountries;
}
#RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseBody
public Country getCountryById(#PathVariable int id) {
return countryService.getCountry(id);
}
.
.
.
}
And in case you are having a rest call which doesn't return anything then make sure to write #ResponseStatus(HttpStatus.NO_CONTENT)
Example:
#RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseStatus(HttpStatus.NO_CONTENT)
public void setCountryById(#PathVariable int id) {
countryService.setCountry(id);
}
Hello i am converting my simple demo project from bean configuration to pure java based configuration. Bean configuration works fine creating tables and all. But my java configuration is not displaying any pages. I solved many errors bur now console shows no error specifying the problem. here's my code please find whats wrong, or have i missed anything in the configuration. I am new to spring and fairly new to java based configuration. These are the sites from which i took code.
http://codehustler.org/blog/spring-security-tutorial-form-login-java-config/
for hibernate i use used this tutorial
http://websystique.com/spring/spring4-hibernate4-mysql-maven-integration-example-using-annotations/
My classes
1. AppConfiguration
package com.kharoud.configuration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
#Configuration
#ComponentScan({"com.kharoud"})
#Import({MvcConfiguraion.class, RepositoryConfiguration.class})
public class AppConfiguration {
}
2.MvcConfigurtion
package com.kharoud.configuration;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#EnableWebMvc
#Configuration
public class MvcConfiguraion extends WebMvcConfigurerAdapter{
#Override
public void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer ){
configurer.enable();
}
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views");
resolver.setSuffix(".jsp");
return resolver;
}
}
3.RepositoryConfiguration
package com.kharoud.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#PropertySource({ "classpath:hibernate.properties" })
public class RepositoryConfiguration {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] {"com.kharoud.model"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
4.SpringConfigurationInitializer
package com.kharoud.configuration.initilizer;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.kharoud.configuration.AppConfiguration;
public class SpringConfigurationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfiguration.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
only added these new classes. I deleted my web.xml.
Later on i will add Spring Security configuration class
this is my console output
Feb 25, 2015 2:32:13 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_25\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Window s;C:/Program Files/Java/jre1.8.0_25/bin/server;C:/Program Files/Java/jre1.8.0_25/bin;C:/Program Files/Java/jre1.8.0_25/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Windows\ system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShe ll\v1.0\;C:\Program Files\Java\jdk1.8.0_25\bin;;C:\ECLIPSE\eclipse;;.
Feb 25, 2015 2:32:14 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:ProjectDemo' did not find a matching property.
Feb 25, 2015 2:32:14 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Feb 25, 2015 2:32:14 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Feb 25, 2015 2:32:14 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1063 ms
Feb 25, 2015 2:32:14 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Feb 25, 2015 2:32:14 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47
Feb 25, 2015 2:32:15 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [217] milliseconds.
Feb 25, 2015 2:32:18 PM org.apache.catalina.core.ApplicationContext log
INFO: Spring WebApplicationInitializers detected on classpath: [com.kharoud.configuration.initilizer.SpringConfigurationInitializer#389ae113]
Feb 25, 2015 2:32:18 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader).
log4j:WARN Please initialize the log4j system properly.
Feb 25, 2015 2:32:26 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcher'
Feb 25, 2015 2:32:26 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Feb 25, 2015 2:32:26 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Feb 25, 2015 2:32:26 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 11876 ms
MyHomeController
package com.kharoud;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/")
public String welcome(Model model){
return "index";
}
}
Myindex.jsp file is in WEB-INF/views folder under webapp folder
The views were properly resolved with bean configuration.
Thank you for your answers. I found the problem. When i wrote #ComponentScan on top of my MvcConfiguration class it worked and pages are displaying.
Using Java and hibernate, I was to change the Database definition after creation, just by making changes to my existing Entity Class. Will the Changes be reflected in the Database??? Is it Possible??? I tried and Failed. I have tried <property name="hibernate.hbm2ddl.auto">update</property> But getting error, Can anyone guide me with the proper method, here is my code.
/**
* Description of bankbranchcontactdetailsBean
*
* #author Vishal Jain # TurtleTec Inc.
*/
package com.beans;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Temporal;
import javax.persistence.UniqueConstraint;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.io.Serializable;
import java.util.Date;
#Entity(name = "bankbranchcontactdetails")
#Table(name = "bankbranchcontactdetails", schema = "stserptest", uniqueConstraints = { #UniqueConstraint(columnNames = "BankBranchContactId") })
#TableGenerator(name = "bankbranchcontactdetailsgen", table = "bankbranchcontactdetails", pkColumnName = "BankBranchContactId")
public class bankbranchcontactdetailsBean extends SuperBeanClass implements
SuperBeanInterface, Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(columnDefinition = "INT(10) UNSIGNED", name = "BankBranchContactId", precision = 10, scale = 0, nullable = false, unique = true)
private Integer Id;
#Column(columnDefinition = "INT(10) UNSIGNED", name = "BankBranchId", precision = 10, scale = 0, nullable = false)
private Integer _BankBranchId;
#Column(columnDefinition = "ENUM('PHONE','MOBILE','FAX','TELEX')", name = "ContactTypeModified", length = 6, nullable = false)
private String _ContactTypeModified;
#Column(columnDefinition = "VARCHAR(20)", name = "Contact", length = 20, nullable = false)
private String _Contact;
#Column(columnDefinition = "INT(10) UNSIGNED", name = "NewField", precision = 10, scale = 0, nullable = true)
private Integer _NewField;
public bankbranchcontactdetailsBean() {
_BankBranchId = 0;
_ContactType = "";
_Contact = "";
_NewField = 0;
}
public bankbranchcontactdetailsBean(Integer __BankBranchId,
String __ContactTypeModified String __Contact, Integer __MyCompanyId) {
_BankBranchId = __BankBranchId;
_ContactTypeModified = __ContactTypeModified;
_Contact = __Contact;
_MyCompanyId = __MyCompanyId;
}
public int getBankBranchContactId() {
return Id;
}
public Integer getBankBranchId() {
return _BankBranchId;
}
public String getContactType() {
return _ContactTypeModified;
}
public String getContact() {
return _Contact;
}
public Integer getNewField() {
return _NewField;
}
public void setBankBranchContactId(int NewValue) {
Id = NewValue;
}
public void setBankBranchId(Integer NewValue) {
_BankBranchId = NewValue;
}
public void setContactType(String NewValue) {
_ContactTypeModified = NewValue;
}
public void setContact(String NewValue) {
_Contact = NewValue;
}
public void setNewField(Integer NewValue) {
_NewField = NewValue;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">V32</property>
<property name="hibernate.default_schema">stserptest</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.archive.autodetection">class</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="com.stserp.beans.bankbranchcontactdetailsBean" />
</session-factory>
</hibernate-configuration>
/**
* Description of ManagerClass
*
* #author Vishal Jain
*/
package com.beans;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class ManagerClass {
private static SessionFactory factory = null;
private static ManagerClass _ManagerClass = null;
public static SessionFactory createSessionFactory() {
SessionFactory sessionFactory;
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return factory;
}
public static ManagerClass getInstance() throws ExceptionInInitializerError {
try {
if (factory == null) {
factory = createSessionFactory();
}
if (_ManagerClass == null) {
_ManagerClass = new ManagerClass();
}
} catch (Throwable ex) {
JOptionPane.showMessageDialog(
null,
"Failed to create sessionFactory object...\n"
+ ex.getMessage(), "Error...", 0);
throw new ExceptionInInitializerError(ex);
} finally {
return _ManagerClass;
}
}
public ArrayList<Integer> SaveBeansList(Session session, String entityName,
ArrayList<? extends SuperBeanClass> BeansList)
throws HibernateException {
ArrayList<Integer> IDs = null;
try {
IDs = new ArrayList<Integer>();
for (SuperBeanClass element : BeansList) {
IDs.add((Integer) session.save(entityName, element));
}
} catch (HibernateException e) {
throw e;
}
return IDs;
}
public ArrayList<? extends SuperBeanClass> LoadTable(Session session,
String TableName) throws HibernateException {
ArrayList<? extends SuperBeanClass> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery("FROM " + TableName).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public ArrayList<?> LoadConditional(Session session, String _query)
throws HibernateException {
ArrayList<?> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery(_query).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public SuperBeanInterface LoadById(Session session, Class className,
Integer ID) throws HibernateException {
SuperBeanInterface BeanInterface = null;
try {
BeanInterface = (SuperBeanInterface) session.get(className, ID);
} catch (HibernateException e) {
throw e;
}
return BeanInterface;
}
public void DeleteById(Session session, Class className, Integer ID)
throws HibernateException {
try {
session.delete(session.get(className, ID));
} catch (HibernateException e) {
throw e;
}
}
}
/**
* Description of SuperBeanClass
*
* #author Vishal Jain
*/
package com.beans;
public class SuperBeanClass {
public SuperBeanClass() {
}
}
/**
* Description of SuperBeanInterface
*
* #author Vishal Jain
*/
package com.beans;
public interface SuperBeanInterface {
}
Here the field 'ContactType' has been Changed to 'ContactTypeModified' and a new Field 'NewField' has been added to the Entity Class bankbranchcontactdetailsBean. No manual changes have been made to the existing Database Table bankbranchcontactdetails. I am getting Error upon the execution of the program which is as Follows :
Aug 14, 2014 10:13:59 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Aug 14, 2014 10:13:59 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.6.Final}
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Aug 14, 2014 10:13:59 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull]
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Aug 14, 2014 10:13:59 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 14, 2014 10:13:59 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Aug 14, 2014 10:13:59 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000388: Unsuccessful: create table stserptest.bankbranchcontactdetails (BankBranchContactId INT(10) UNSIGNED not null auto_increment, BankBranchId INT(10) UNSIGNED not null, Contact VARCHAR(20) not null, ContactTypeModified ENUM('PHONE','MOBILE','FAX','TELEX') not null, EntryDate TIMESTAMP, MyCompanyId INT(10) UNSIGNED not null, NewField INT(10) UNSIGNED, UserId INT(10) UNSIGNED, isDeleted ENUM('YES','NO'), primary key (BankBranchContactId))
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: Table 'bankbranchcontactdetails' already exists
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Aug 14, 2014 10:14:00 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Aug 14, 2014 10:14:00 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Aug 14, 2014 10:14:00 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Aug 14, 2014 10:14:00 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull]
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Aug 14, 2014 10:14:00 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 14, 2014 10:14:00 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Aug 14, 2014 10:14:00 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000388: Unsuccessful: create table stserptest.bankbranchcontactdetails (BankBranchContactId INT(10) UNSIGNED not null auto_increment, BankBranchId INT(10) UNSIGNED not null, Contact VARCHAR(20) not null, ContactTypeModified ENUM('PHONE','MOBILE','FAX','TELEX') not null, EntryDate TIMESTAMP, MyCompanyId INT(10) UNSIGNED not null, NewField INT(10) UNSIGNED, UserId INT(10) UNSIGNED, isDeleted ENUM('YES','NO'), primary key (BankBranchContactId))
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: Table 'bankbranchcontactdetails' already exists
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate:
insert
into
stserptest.bankbranchcontactdetails
(BankBranchId, Contact, ContactTypeModified, EntryDate, MyCompanyId, NewField, UserId, isDeleted)
values
(?, ?, ?, ?, ?, ?, ?, ?)
Aug 14, 2014 10:14:00 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
Aug 14, 2014 10:14:00 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'ContactTypeModified' in 'field list'
This question already has answers here:
Hibernate - does it change the structure of a database?
(3 answers)
Closed 8 years ago.
Using Java and hibernate, I was wondering that if I can change the Database definition after creation, just by making changes to my existing Entity Class. Will the Changes be reflected in the Database??? Is it Possible??? I tried and Failed. I have tried
<property name="hibernate.hbm2ddl.auto">update</property>
But getting error, if it is still possible, here is my code.
/**
* Description of bankbranchcontactdetailsBean
*
* #author Vishal Jain # TurtleTec Inc.
*/
package com.beans;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.Temporal;
import javax.persistence.UniqueConstraint;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.io.Serializable;
import java.util.Date;
#Entity(name = "bankbranchcontactdetails")
#Table(name = "bankbranchcontactdetails", schema = "stserptest", uniqueConstraints = { #UniqueConstraint(columnNames = "BankBranchContactId") })
#TableGenerator(name = "bankbranchcontactdetailsgen", table = "bankbranchcontactdetails", pkColumnName = "BankBranchContactId")
public class bankbranchcontactdetailsBean extends SuperBeanClass implements
SuperBeanInterface, Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(columnDefinition = "INT(10) UNSIGNED", name = "BankBranchContactId", precision = 10, scale = 0, nullable = false, unique = true)
private Integer Id;
#Column(columnDefinition = "INT(10) UNSIGNED", name = "BankBranchId", precision = 10, scale = 0, nullable = false)
private Integer _BankBranchId;
#Column(columnDefinition = "ENUM('PHONE','MOBILE','FAX','TELEX')", name = "ContactTypeModified", length = 6, nullable = false)
private String _ContactTypeModified;
#Column(columnDefinition = "VARCHAR(20)", name = "Contact", length = 20, nullable = false)
private String _Contact;
#Column(columnDefinition = "INT(10) UNSIGNED", name = "NewField", precision = 10, scale = 0, nullable = true)
private Integer _NewField;
public bankbranchcontactdetailsBean() {
_BankBranchId = 0;
_ContactType = "";
_Contact = "";
_NewField = 0;
}
public bankbranchcontactdetailsBean(Integer __BankBranchId,
String __ContactTypeModified String __Contact, Integer __MyCompanyId) {
_BankBranchId = __BankBranchId;
_ContactTypeModified = __ContactTypeModified;
_Contact = __Contact;
_MyCompanyId = __MyCompanyId;
}
public int getBankBranchContactId() {
return Id;
}
public Integer getBankBranchId() {
return _BankBranchId;
}
public String getContactType() {
return _ContactTypeModified;
}
public String getContact() {
return _Contact;
}
public Integer getNewField() {
return _NewField;
}
public void setBankBranchContactId(int NewValue) {
Id = NewValue;
}
public void setBankBranchId(Integer NewValue) {
_BankBranchId = NewValue;
}
public void setContactType(String NewValue) {
_ContactTypeModified = NewValue;
}
public void setContact(String NewValue) {
_Contact = NewValue;
}
public void setNewField(Integer NewValue) {
_NewField = NewValue;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">V32</property>
<property name="hibernate.default_schema">stserptest</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.archive.autodetection">class</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<mapping class="com.stserp.beans.bankbranchcontactdetailsBean" />
</session-factory>
</hibernate-configuration>
/**
* Description of ManagerClass
*
* #author Vishal Jain
*/
package com.beans;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class ManagerClass {
private static SessionFactory factory = null;
private static ManagerClass _ManagerClass = null;
public static SessionFactory createSessionFactory() {
SessionFactory sessionFactory;
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
return factory;
}
public static ManagerClass getInstance() throws ExceptionInInitializerError {
try {
if (factory == null) {
factory = createSessionFactory();
}
if (_ManagerClass == null) {
_ManagerClass = new ManagerClass();
}
} catch (Throwable ex) {
JOptionPane.showMessageDialog(
null,
"Failed to create sessionFactory object...\n"
+ ex.getMessage(), "Error...", 0);
throw new ExceptionInInitializerError(ex);
} finally {
return _ManagerClass;
}
}
public ArrayList<Integer> SaveBeansList(Session session, String entityName,
ArrayList<? extends SuperBeanClass> BeansList)
throws HibernateException {
ArrayList<Integer> IDs = null;
try {
IDs = new ArrayList<Integer>();
for (SuperBeanClass element : BeansList) {
IDs.add((Integer) session.save(entityName, element));
}
} catch (HibernateException e) {
throw e;
}
return IDs;
}
public ArrayList<? extends SuperBeanClass> LoadTable(Session session,
String TableName) throws HibernateException {
ArrayList<? extends SuperBeanClass> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery("FROM " + TableName).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public ArrayList<?> LoadConditional(Session session, String _query)
throws HibernateException {
ArrayList<?> beansList = null;
try {
beansList = (ArrayList<? extends SuperBeanClass>) session
.createQuery(_query).list();
} catch (HibernateException e) {
throw e;
}
return beansList;
}
public SuperBeanInterface LoadById(Session session, Class className,
Integer ID) throws HibernateException {
SuperBeanInterface BeanInterface = null;
try {
BeanInterface = (SuperBeanInterface) session.get(className, ID);
} catch (HibernateException e) {
throw e;
}
return BeanInterface;
}
public void DeleteById(Session session, Class className, Integer ID)
throws HibernateException {
try {
session.delete(session.get(className, ID));
} catch (HibernateException e) {
throw e;
}
}
}
/**
* Description of SuperBeanClass
*
* #author Vishal Jain
*/
package com.beans;
public class SuperBeanClass {
public SuperBeanClass() {
}
}
/**
* Description of SuperBeanInterface
*
* #author Vishal Jain
*/
package com.beans;
public interface SuperBeanInterface {
}
Here the field 'ContactType' has been Changed to 'ContactTypeModified' and a new Field 'NewField' has been added to the Entity Class. No manual changes have been made to the Database. I am getting Error upon the execution of the program which is as Follows :
Aug 14, 2014 10:13:59 AM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Aug 14, 2014 10:13:59 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.6.Final}
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Aug 14, 2014 10:13:59 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Aug 14, 2014 10:13:59 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull]
Aug 14, 2014 10:13:59 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Aug 14, 2014 10:13:59 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 14, 2014 10:13:59 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Aug 14, 2014 10:13:59 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000388: Unsuccessful: create table stserptest.bankbranchcontactdetails (BankBranchContactId INT(10) UNSIGNED not null auto_increment, BankBranchId INT(10) UNSIGNED not null, Contact VARCHAR(20) not null, ContactTypeModified ENUM('PHONE','MOBILE','FAX','TELEX') not null, EntryDate TIMESTAMP, MyCompanyId INT(10) UNSIGNED not null, NewField INT(10) UNSIGNED, UserId INT(10) UNSIGNED, isDeleted ENUM('YES','NO'), primary key (BankBranchContactId))
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: Table 'bankbranchcontactdetails' already exists
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Aug 14, 2014 10:14:00 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Aug 14, 2014 10:14:00 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Aug 14, 2014 10:14:00 AM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Aug 14, 2014 10:14:00 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull]
Aug 14, 2014 10:14:00 AM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root, password=****}
Aug 14, 2014 10:14:00 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Aug 14, 2014 10:14:00 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Aug 14, 2014 10:14:00 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.DatabaseMetadata getTableMetadata
INFO: HHH000262: Table not found: bankbranchcontactdetails
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: HHH000388: Unsuccessful: create table stserptest.bankbranchcontactdetails (BankBranchContactId INT(10) UNSIGNED not null auto_increment, BankBranchId INT(10) UNSIGNED not null, Contact VARCHAR(20) not null, ContactTypeModified ENUM('PHONE','MOBILE','FAX','TELEX') not null, EntryDate TIMESTAMP, MyCompanyId INT(10) UNSIGNED not null, NewField INT(10) UNSIGNED, UserId INT(10) UNSIGNED, isDeleted ENUM('YES','NO'), primary key (BankBranchContactId))
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
ERROR: Table 'bankbranchcontactdetails' already exists
Aug 14, 2014 10:14:00 AM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate:
insert
into
stserptest.bankbranchcontactdetails
(BankBranchId, Contact, ContactTypeModified, EntryDate, MyCompanyId, NewField, UserId, isDeleted)
values
(?, ?, ?, ?, ?, ?, ?, ?)
Aug 14, 2014 10:14:00 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
Aug 14, 2014 10:14:00 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'ContactTypeModified' in 'field list'
Hibernate can modify the db structure if you set it into update mode
<property name="hbm2ddl.auto">update</property>
However it might be better to use something like liquibase or Flyaway that will keep track of the versioning of the tables over time.
In my experience relying on hibernate to keep the schema in sync with the entity models won't work in the long run, especially if you have any kind of branching in your project. You would be opening yourself up for dataloss, unless you instruct it on how to mutate the columns to preserve all of the information inside. Hibernate can very well just choose to drop a column and add a new one, when all you wanted was to rename; this would be bad.
However if you are using an embedded in-memory db (like hsqldb) and do not care about persisting data between executions, then yes you can simply setup hibernate to use the create or create-drop mode and it will construct the tables to match your entities.
as In topic my war is running without errors on Jetty / Tomcat but when I deploy it to the Resin 4
It shows as running / active in the deployed applications tab on the resin-admin panel. Nothing unusual in the logs as well.
But when I try to access myapp I am getting 404
Aug 14, 2013 9:20:25 AM com.caucho.server.cluster.Server start
INFO: resin.conf = null
Aug 14, 2013 9:20:25 AM com.caucho.server.cluster.Server start
INFO:
Aug 14, 2013 9:20:25 AM com.caucho.lifecycle.Lifecycle toActive
INFO: Host[] active
Aug 14, 2013 9:20:25 AM com.caucho.server.port.Port bind
INFO: http listening to *:8080
Aug 14, 2013 9:20:25 AM com.caucho.lifecycle.Lifecycle toActive
INFO: Server[id=,cluster=] active
Aug 14, 2013 9:20:25 AM com.caucho.server.resin.Resin start
INFO: Resin started in 2804ms
Aug 14, 2013 9:20:25 AM com.caucho.lifecycle.Lifecycle toStopping
INFO: Host[] stopping
Aug 14, 2013 9:20:25 AM com.caucho.lifecycle.Lifecycle toActive
INFO: Host[] active
Aug 14, 2013 9:20:26 AM com.caucho.lifecycle.Lifecycle toActive
INFO: WebApp[http://localhost:8080/myapp] active
web 3.0 app initializer
import com.opensymphony.sitemesh.webapp.SiteMeshFilter;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
#Order(1)
public class AppWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfiguration.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
return new Filter[] { new SiteMeshFilter() };
}