Hibernate not creating table in H2 - java

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.

Related

Reading and writing xml file to database in spring boot

i have problem with service xml file. I dont get any errors but my xml file dont writing to mysql.
Program only create some batch and task tables in mysql, but doesn't write value into them.
I'm new in springboot and don't have any idea whats wrong with this code.
Here is my BatchConfiguration class.
package com.projekt.springboot;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.database.ItemPreparedStatementSetter;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.xml.StaxEventItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.oxm.xstream.XStreamMarshaller;
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
#Autowired
public JobBuilderFactory jobBuilderFactory;
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Autowired
private DataSource dataSource;
#Bean
public StaxEventItemReader<Task> reader(){
StaxEventItemReader<Task> reader = new StaxEventItemReader<Task>();
reader.setResource(new ClassPathResource("new1.xml"));
reader.setFragmentRootElementName("task");
Map<String, String> aliases = new HashMap<String, String>();
aliases.put("user", "com.projekt.springboot.Task");
XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();
xStreamMarshaller.setAliases(aliases);
reader.setUnmarshaller(xStreamMarshaller);
System.out.println(reader);
return reader;
}
#Bean
public JdbcBatchItemWriter<Task> writer(){
JdbcBatchItemWriter<Task> writer = new JdbcBatchItemWriter<Task>();
writer.setDataSource(dataSource);
writer.setSql("INSERT INTO task(id,name,surname,login) VALUES (:id,:name,:surname,:login)");
writer.setItemPreparedStatementSetter(new UserItemPreparedStmSetter());
return writer;
}
private class UserItemPreparedStmSetter implements ItemPreparedStatementSetter<Task>{
#Override
public void setValues(Task task, PreparedStatement ps) throws SQLException {
ps.setLong(1, task.getId());
ps.setString(2, task.getName());
ps.setString(3, task.getSurname());
ps.setString(4, task.getLogin());
}
}
#Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.<Task, Task> chunk(10)
.reader(reader())
.writer(writer())
.build();
}
#Bean
public Job importUserJob() {
return jobBuilderFactory.get("importUserJob")
.incrementer(new RunIdIncrementer())
.flow(step1())
.end()
.build();
}
}
Task.class
package com.projekt.springboot;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#XmlRootElement(name = "task")
public class Task {
#GeneratedValue(strategy=GenerationType.AUTO)
#Id
private Long id;
#Column
private String name;
#Column
private String surname;
#Column
private String login;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
}
new1.xml
<?xml version="1.0" encoding="UTF-8"?>
<users>
<user>
<id>1</id>
<name>name1</name>
<surname>surname1</surname>
<login>login1</login>
</user>
<user>
<id>2</id>
<name>name2</name>
<surname>surname2</surname>
<login>login2</login>
</user>
</users>
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/users
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto=update
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.batch.initialize-schema=ALWAYS
spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect

java.sql.Timestamp value; nested exception is java.sql.SQLDataException in Spring-boot project

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

Custom UserDetailsService Impl not being Called in SpringSecurity

My Custom UserDetailsService
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.com.fimd.entidades.Usuario;
import br.com.fimd.service.UsuarioService;
#Transactional(readOnly=true)
#Service("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService{
#Autowired
private UsuarioService usuarioService;
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Usuario usuario = usuarioService.findUserByEmail(email);
if(usuario == null) {
throw new UsernameNotFoundException("Usuário nao encontrado.");
}
return new User(usuario.getEmail(), usuario.getSenha(), usuario.getAuthorities());
}
}
My Security Configuration
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
#Qualifier("userDetailsServiceImpl")
private UserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().disable().
csrf().disable().authorizeRequests()
.antMatchers("/home").permitAll()
.antMatchers("/public/**").permitAll()
.antMatchers("/private/**").hasRole("USER")
//.antMatchers("/admin*").access("hasRole('ROLE_ADMIN')")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
//.addFilterBefore(new JWTAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class)
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/assets/**");
}
#Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
}
My User Entity
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name = "usuarios")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true)
public class Usuario implements UserDetails, Serializable{
private static final long serialVersionUID = 4038437690572999966L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private Long id;
#NotBlank
private String nome;
#NotBlank
private String email;
#NotBlank
private String senha;
#NotBlank
private String cpf;
#Column
private boolean ativo;
#ManyToMany
#JoinTable(name="perfil_usuario", joinColumns=
{#JoinColumn(name="user_id")}, inverseJoinColumns=
{#JoinColumn(name="tipo_perfil")})
private Set<Perfil> perfis = new HashSet<>();
#OneToMany(mappedBy = "usuario", cascade = CascadeType.ALL)
private List<Investimento> investimentos;
#OneToMany(mappedBy = "usuario", cascade = CascadeType.ALL)
private List<Extrato> extratos;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
public Set<Perfil> getPerfis() {
return perfis;
}
public void setPerfis(Set<Perfil> perfis) {
this.perfis = perfis;
}
public List<Investimento> getInvestimentos() {
return investimentos;
}
public void setInvestimentos(List<Investimento> investimentos) {
this.investimentos = investimentos;
}
public List<Extrato> getExtratos() {
return extratos;
}
public void setExtratos(List<Extrato> extratos) {
this.extratos = extratos;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.perfis;
}
#Override
public String getPassword() {
return this.senha;
}
#Override
public String getUsername() {
return this.email;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
My Perfil Entity
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import org.springframework.security.core.GrantedAuthority;
#Entity
public class Perfil implements GrantedAuthority{
private static final long serialVersionUID = 1L;
#Id
private String tipoPerfil;
#ManyToMany(mappedBy="perfis")
private List<Usuario> usuarios;
public List<Usuario> getUsuarios() {
return usuarios;
}
public void setUsuarios(List<Usuario> usuarios) {
this.usuarios = usuarios;
}
public String getTipoPerfil() {
return tipoPerfil;
}
public void setTipoPerfil(String tipoPerfil) {
this.tipoPerfil = tipoPerfil;
}
#Override
public String getAuthority() {
return this.tipoPerfil;
}
}
My Spring Filter Initializer
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
#Configuration
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
When i call a "/private/service" my loadUserByUsername not being called never, my application ever send me a 403 forbidden, access denied.
Why that?
I tried a lot of tutorials from internet and my code seems to be correct, i'm using spring starter 2.0.5.RELEASE
I already tried to call the userDetailsService from a #Bean method in SecurityConfiguration
Your security configuration is not complete, you must provide as well the login information:
.formLogin()
.loginPage("/login.html")
.defaultSuccessUrl("/home")
.failureUrl("/login.html?error=true")
Otherwise all your requests will be unauthorized. Please see this tutorial:
https://www.baeldung.com/spring-security-login
Your Custom UserDetails service will be called only when the application will receive a POST to login url with username and password, otherwise it will not have what data to authorize.

hibernate validator doen't work with Spring MVC application

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.

Why database or table not created when I run my spring and Hibernate project

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

Categories

Resources