I'm following an example project from Spring in action 4th book. However, I was blocked at Chapter5, where using hibernate validator to validate values submit by a form. Here are some related codes:
I hava a model named Spitter:
package spittr;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Spitter {
private Long id;
#NotNull
#Size(min=5, max=16)
private String username;
#NotNull
#Size(min=5, max=25)
private String password;
#NotNull
#Size(min=2, max=30)
private String firstName;
#NotNull
#Size(min=2, max=30)
private String lastName;
private String email;
public Spitter() {
}
public Spitter(String username, String password, String firstName, String lastName, String email) {
this(null, username, password, firstName, lastName, email);
}
public Spitter(Long id, String username, String password, String firstName, String lastName, String email) {
this.id = id;
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that, "firstName", "lastName", "username", "password", "email");
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, "firstName", "lastName", "username", "password", "email");
}
}
Controller collect form data and validate them:
package spittr.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import spittr.Spitter;
import spittr.data.SpitterRepository;
import javax.validation.Valid;
#Controller
#RequestMapping("/spitter")
public class SpitterController {
private SpitterRepository spitterRepository;
#Autowired
public SpitterController(SpitterRepository spitterRepository) {
this.spitterRepository = spitterRepository;
}
#RequestMapping(value = "register", method = RequestMethod.POST)
public String processRegistration(#Valid Spitter spitter, Errors errors) {
System.out.println(errors.hasErrors() + ": has errors...");
if (errors.hasErrors()){
return "registerForm";
}
spitterRepository.save(spitter);
return "redirect:/spitter/" + spitter.getUsername();
}
}
And the config files(Java based):
package spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(
basePackages = {"spittr"},
excludeFilters = {
#Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)
})
public class RootConfig {
}
SpitterWebInitializer:
package spittr.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import spittr.web.WebConfig;
public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
WebConfig
package spittr.web;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
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;
#Configuration
#EnableWebMvc
#ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
build.gradle file:
apply plugin: 'war'
apply plugin: 'idea'
apply plugin: 'java'
//apply from: 'gretty.plugin'
apply plugin: 'com.bmuschko.tomcat'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.bmuschko:gradle-tomcat-plugin:2.2.2'
}
}
dependencies {
compile "org.springframework:spring-webmvc:4.0.7.RELEASE"
compile "org.springframework:spring-jdbc:4.0.7.RELEASE"
compile "org.hibernate:hibernate-validator:5.3.2.Final"
//providedCompile "org.glassfish.web:javax.el:2.2.4"
// https://mvnrepository.com/artifact/javax.validation/validation-api
providedCompile group: 'javax.validation', name: 'validation-api', version: '1.1.0.Final'
compile "javax.servlet:jstl:1.2"
compile "org.apache.commons:commons-lang3:3.1"
def tomcatVersion = '7.0.59'
tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
"org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}",
"org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}"
providedCompile "javax.servlet.jsp:jsp-api:2.1"
providedCompile "javax.el:javax.el-api:2.2.4"
providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}
maven { url 'http://maven.springframework.org/release' }
maven { url 'http://maven.springframework.org/milestone' }
maven { url 'http://maven.springframework.org/snapshot' }
maven { url 'http://download.java.net/maven/2' }
mavenCentral()
}
war {
baseName = 'spittr'
version = '0.1.0'
}
tomcat {
httpPort = 8080
httpsPort = 8443
enableSSL = true
// contextPath = 'sample-app'
}
Full porject available at GitHub: https://github.com/zmrenwu/Spittr
I spend several days on Google and Stackoverflow for searching sulutions, but no luck.
Please give me some help, thanks!
I'm not familiar with Gradle but I think it will work if you delete this line :
providedCompile group: 'javax.validation', name: 'validation-api', version: '1.1.0.Final'
At least I tested it with Maven and it solved the problem.
Add #Validated annotation to your controller class:
#Controller
#Validated
#RequestMapping("/spitter")
public class SpitterController {
...
hibernate-validator is by default is using javax.validation:validation-api:jar:1.1.0.Final
[INFO] | +- org.hibernate.validator:hibernate-validator:jar:6.0.12.Final:compile
[INFO] | | +- (javax.validation:validation-api:jar:1.1.0.Final:
Try to upgrade to latest version javax.validation:validation-api:2.0.1.Final this worked for me.
Related
I'm building a project with spring boots, checking the status of the Internet through control, and I'm in the process of a DB connection.
I'm trying to do 'MyBatis', but there's an error.
This is a list of my directories:
MinitoringdataApplication.java
package com.smartcore.mn.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
#MapperScan(basePackages = "com.smartcore.mn.springboot")
public class MinitoringdataApplication {
public static void main(String[] args) {
SpringApplication.run(MinitoringdataApplication.class, args);
}
}
ServletInitializer.java
package com.smartcore.mn.springboot;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MinitoringdataApplication.class);
}
}
ApiController.java
package com.smartcore.mn.springboot.controller;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.smartcore.mn.springboot.model.Member;
import com.smartcore.mn.springboot.service.MemberService;
#RestController
public class ApiController {
#Autowired
MemberService memberService;
#GetMapping(path = "/helloWorld")
public String helloWorld() {
return LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
#GetMapping(path = "/db")
public List<Member> selectAllMember() {
List<Member> members = memberService.getAllMember();
return members;
}
}
MemberMapper.interface
package com.smartcore.mn.springboot.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import com.smartcore.mn.springboot.model.Member;
#Mapper
public interface MemberMapper {
Member selectMemberById(Long id);
List<Member> selectAllMember();
void insertMember(Member member);
}
Member.java
package com.smartcore.mn.springboot.model;
import java.util.Date;
import org.apache.ibatis.type.Alias;
import com.smartcore.mn.springboot.Exception.IdPasswordNotMatchingException;
import lombok.Data;
#Data
#Alias("member")
public class Member {
private Long id;
private String email;
private String password;
private String name;
private Date registerDate;
public Member(String email, String password, String name, Date registerDate) {
this.email = email;
this.password = password;
this.name = name;
this.registerDate = registerDate;
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public String getName() {
return name;
}
public Date getRegisterDate() {
return registerDate;
}
public void changePassword(String oldPassword, String newPassword) {
if (!password.equals(oldPassword))
throw new IdPasswordNotMatchingException();
this.password = newPassword;
}
}
MemberService.java
package com.smartcore.mn.springboot.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.smartcore.mn.springboot.mapper.MemberMapper;
import com.smartcore.mn.springboot.model.Member;
#Service
#Transactional
public class MemberService {
#Autowired
MemberMapper memberMapper;
public Member getMemberById(Long id) {
return memberMapper.selectMemberById(id);
}
public List<Member> getAllMember() {
return memberMapper.selectAllMember();
}
public void addMember(Member member) {
memberMapper.insertMember(member);
}
}
application.properties
spring.datasource.url=jdbc:mysql://localhost/mydb?serverTimezone=UTC&autoReconnection=true
spring.datasource.username=mydb
spring.datasource.password=mydb
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.type-aliases-package=com.smartcore.mn.springboot.model
logging.level.com.smartcore.mn.springboot.mapper=TRACE
MemberMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.smartcore.mn.springboot.mapper.MemberMapper">
<select id="selectMemberById" resultType="member">
SELECT *
FROM MEMBER
WHERE ID = #{id}
</select>
<select id="selectAllMember" resultType="member">
SELECT *
FROM MEMBER
</select>
<insert id="insertMember">
INSERT INTO MEMBER (EMAIL, PASSWORD, NAME, REGDATE)
VALUES (#{email}, #{password}, #{name}, #{registerDate})
</insert>
</mapper>
http://localhost:8080/helloworld is works normally.
But http://localhost:8080/db have see Error
I need your solution. Thank you in advance.
my TABLE
As mentioned in our discussion in comments, MyBatis is trying to map your NAME column in result-set to the registerDate argument in the Member constructor.
Since you did not specify paramName for each fields, the order of arg elements in the constructor is error-prone.
Try mapping your result-set to your constructor with correct ordered args:
Member(String email, String password, String name, Date registerDate) should match SELECT EMAIL, PASSWORD, NAME, REGDATE FROM MEMBER
or
Member(Long id, String email, String password, String name, Date registerDate) should match SELECT * FROM MEMBER
I am not sure what is wrong with my codes. I was trying to learn Spring Boot WebFlux. But I am not able to run the application as i get the below error
" Parameter 0 of constructor in com.thomsoncodes.todo.controller.ToDoController required a bean of type 'com.thomsoncodes.todo.repository.ToDoRespository' that could not be found."
Tired #Autowired but still I have the same error.
Here is my code
build.gradle
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
id 'java'
}
apply plugin: 'io.spring.dependency-management'
group = 'com.thomsoncodes.todo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-webflux'
compileOnly 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
}
Application class
package com.thomsoncodes.todo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootTodoWebfluxApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootTodoWebfluxApplication.class, args);
}
}
Controller class
package com.thomsoncodes.todo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.thomsoncodes.todo.domain.ToDo;
import com.thomsoncodes.todo.repository.ToDoRespository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
#RestController
public class ToDoController {
private ToDoRespository repository;
public ToDoController(ToDoRespository repository) {
this.repository = repository;
}
#GetMapping("/rodo/{id}")
public Mono<ToDo> getTodo(#PathVariable String id) {
return this.repository.findById(id);
}
#GetMapping("/todo")
public Flux<ToDo> getToDos() {
return this.repository.findAll();
}
}
domain class
package com.thomsoncodes.todo.domain;
import java.time.LocalDateTime;
import java.util.UUID;
import lombok.Data;
#Data
public class ToDo {
private String id;
private String description;
private LocalDateTime created;
private LocalDateTime modified;
private boolean completed;
public ToDo() {
this.id = UUID.randomUUID().toString();
this.created = LocalDateTime.now();
this.modified = LocalDateTime.now();
}
public ToDo(String description) {
this();
this.description = description;
}
public ToDo(String description, boolean completed) {
this();
this.description = description;
this.completed = completed;
}
}
Repository class
package com.thomsoncodes.todo.repository;
import java.util.Arrays;
import com.thomsoncodes.todo.domain.ToDo;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
public class ToDoRespository {
private Flux<ToDo> toDoFlux = Flux.fromIterable(Arrays.asList(
new ToDo("Do Homework"),
new ToDo("Workout in the morning", true),
new ToDo("Make dinner tonight"),
new ToDo("Clean the studio", true),
new ToDo("Learn spring boot", true)));
public Mono<ToDo> findById(String id) {
return Mono.from(
toDoFlux.filter( todo -> todo.getId().equals(id)));
}
public Flux<ToDo> findAll() {
return toDoFlux;
}
}
You need to make a couple of changes,
Annotate ToDoRepository with #Repository or #Component
Annotate ToDoRepository with #Autowired in controller class (optional)
ToDoRepository isn't marked as #Component.
Yeah, found out adding #AutoConfiguration to the class where the issue is happening usually solves the problem for this bug.
Hibernate is not creating table in H2 database. I am using a maven webapp project. But hibernate seems to not create automatic tables. PLease help. This is my User class -
package com.sakib.model;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "userlogin")
public class User {
private String fname;
private String lname;
private String email;
private int mobile;
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getMobile() {
return mobile;
}
public void setMobile(int mobile) {
this.mobile = mobile;
}
}
This is my DBConfiguration file. I am not using xml based file for hibernate config -
package com.sakib.configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.sakib.model.User;
public class DBConfiguration {
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:tcp://localhost/~/userlogin");
dataSource.setUsername("sa");
dataSource.setPassword("sa");
return dataSource;
}
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder lsf=
new LocalSessionFactoryBuilder(getDataSource());
Properties hibernateProperties=new Properties();
hibernateProperties.setProperty(
"hibernate.dialect", "org.hibernate.dialect.H2Dialect");
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create");
hibernateProperties.setProperty("hibernate.show_sql", "true");
lsf.addProperties(hibernateProperties);
Class classes[]=new Class[]{User.class};
return lsf.addAnnotatedClasses(classes).buildSessionFactory();
}
#Bean
public HibernateTransactionManager hibTransManagement(){
return new HibernateTransactionManager(sessionFactory());
}
}
This is App.java. Its basically to run backend implementation with main method -
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.sakib.configuration.DBConfiguration;
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
ApplicationContext context=
new AnnotationConfigApplicationContext(DBConfiguration.class);
}
}
Any help would be of great use.
When i run my project It sun successfully but table is not created. where i am doing wrong
My Hibernate configuration class
package com.quickstart.com.springmvc.config;
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.ComponentScan;
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
#ComponentScan({ "com.quickstart.com.springmvc.config" })
#PropertySource(value = { "classpath:application.properties" })
public class HibernateConfigration {
#Autowired
private Environment environment;
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.quickstart.com.springmvc.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#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"));
System.out.println(environment.getRequiredProperty("jdbc.username"));
return dataSource;
}
private 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.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
My SpringConfigration class
package com.quickstart.com.springmvc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#ComponentScan(basePackages="com.quickstart.com.springmvc")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
My User Class
package com.quickstart.com.springmvc.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Service;
#Service
#Entity
#Table(name="user")
public class User {
#Id
#Column(name="user_id")
private int id;
#Column(name="Name")
private String name;
#Column(name="Email")
private String email;
#Column(name="Age")
private int age;
#Column(name="Password")
private String password;
#Column(name="Contact")
private String contact;
#Column(name="User_Name")
private String username;
User(){
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
User(String name){
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
my properties file
jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url =
jdbc:mysql://localhost:3306/HibernateTestDB jdbc.username = root
jdbc.password = root hibernate.dialect =
org.hibernate.dialect.MySQLDialect hibernate.show_sql = true
hibernate.format_sql = true
You forgot this option hibernate.hbm2ddl.auto in your properties :
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
This property can have the following values :
create creates the schema, destroying previous data
create-drop drop the schema when the SessionFactory is closed explicitly, typically when the application is stopped.
update update the schema.
validate validate the schema, makes no changes to the database.
Add a property in your hibernate configuration properties file
hibernate.hbm2ddl.auto = create
The other available values are "update" "create-drop" "validate" etc
See "Table 3.7. Miscellaneous Properties" https://docs.jboss.org/hibernate/orm/5.0/manual/en-US/html/ch03.html
I follow this tutorial: http://spring.io/guides/gs/rest-service/
This is my project structure:
build.gradle
buildscript{
repositories{
mavenCentral()
}
dependencies{
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
jar{
baseName = 'gs-rest-service'
version = '0.1.0'
}
repositories{
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies{
compile("org.springframework.boot:spring-boot-starter-web")
testCompile("junit:junit")
}
task wrapper(type: Wrapper){
gradleVersion = '2.3'
}
Application.java
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Greeting.java
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
super();
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
GreetingControler.java
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
I know how to run Spring Boot application by gradle bootRun command (run on Apache Tomcat embed server). But I don't know how to run above Spring Boot application on real Apache Tomcat (Please help me at this point!)
Follow comments's manish, I create source base from http://start.spring.io/
Then I import to Eclipse for Java EE (with Spring Tools Suite, Gradle plugin), this is project folder structure:
Greeting.java
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
GreetingController
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#RequestMapping("/greeting")
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
I modified file GsRestServiceApplication.java
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class GsRestServiceApplication {
public static void main(String[] args) {
SpringApplication.run(GreetingController.class, args); // <-- modify this line.
}
}
I don't change file GsRestServiceApplication.java
package hello;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(GsRestServiceApplication.class);
}
}
I can run web app in real Tomcat server:
Then I use browser or Postman to view result:
http://localhost:8080/gs-rest-service/greeting?name=Vy
You're using Gradle. Try to add this in your build.gradle file.
dependencies {
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}
Don't forget to remove:
compile("org.springframework.boot:spring-boot-starter-web")