This question already has answers here:
Spring Boot Hibernate 5 Ignoring #Table and #Column
(2 answers)
Closed 5 years ago.
I try to use CrudRepository on my work. And When the sql request appear on my log, It's just abnormal.
The real table is 'AllDatabase.AllUserInfo' but the generated sql request look like 'all_user_info alluresinf0_', which is unusable.
I have been all over the internet and nobody seems to face my problem (as far as I know). So please somebody tell me if I'm missing some configuration in my project.
I work on Intellij Idea with 'Spring Initializer' with 'Web' , 'JPA' , 'MySQL' selected. These are my code.
here is my Repository
package com.chuchurest.proj.Repository;
import com.chuchurest.proj.Entity.AllUserInfo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by slimshady23 on 6/25/2017 AD.
*/
#Transactional
#Repository
public interface UserRepository extends CrudRepository<AllUserInfo,String> {
}
here is The 'AllUserInfo' Entity
package com.chuchurest.proj.Entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.io.Serializable;
/**
* Created by slimshady23 on 6/23/2017 AD.
*/
#Entity
#Table(name = "AllUserInfo")
public class AllUserInfo {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private String Id;
#Column(name="username")
private String Username;
#Column(name="password")
private String Password;
#Column(name="email")
private String Email;
#Column(name="phone")
private String Phone;
#Column(name="rating")
private Integer Rating;
#Column(name="skill")
private Integer Skill;
#Column(name="description")
private String Description;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public Integer getRating() {
return Rating;
}
public void setRating(Integer rating) {
Rating = rating;
}
public Integer getSkill() {
return Skill;
}
public void setSkill(Integer skill) {
Skill = skill;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
And this is how I invoke the save() method
package com.chuchurest.proj.Service;
import com.chuchurest.proj.DAO.UserInfoDAO;
import com.chuchurest.proj.Entity.AllUserInfo;
import com.chuchurest.proj.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by slimshady23 on 6/24/2017 AD.
*/
#Service
public class AppService {
#Autowired
private UserRepository userRepository;
public void PerformRegister(AllUserInfo userinfo)
{
userRepository.save(userinfo);
}
}
And here is the Application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/AllDatabase
spring.datasource.username=root
spring.datasource.password= ******
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.show-sql= true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Note the dot, the difference between schema.tablename and tablename alias
The AllUserInfo_f0 is an alias for AllUserInfo. It's used in Hibernate by default for supporting query relations on the same table multiple times. It doesn't break your sql.
Related
I'm trying to make a blog using spring boot java with auth.
I created User class the implements UserDetails, and Post class.
When using the path /posts I wish to see all the posts in the blog, problem is that each post contains creator (User obj) and it shows the password of the user - and this is what I'm trying to avoid.
I tried #JsonIgnor, #JsonProperty didn't work
Tried also #JsonProperty(access = Access.WRITE_ONLY) I get an error on the Access.WRITE_ONLY.
Does are the classes:
package com.example.blog.entities;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.Collection;
import java.util.List;
#Entity
#Table(name = "users")
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String username;
#JsonIgnore
private String password;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Role> roles;
public User() {}
public User(String username, String password, List<Role> roles) {
this.username = username;
this.password = password;
this.roles = roles;
}
#JsonIgnore
public String getPassword() {
return password;
}
#JsonProperty
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
}
import javax.persistence.*;
import java.time.LocalDate;
import java.util.Date;
#Entity
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String title;
private String body;
private LocalDate date;
#ManyToOne
private User creator;
public Post() {
}
}
import com.example.blog.entities.Post;
import com.example.blog.entities.User;
import com.example.blog.repositories.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;
#Service
public class PostService {
private final PostRepository postRepository;
#Autowired
public PostService(PostRepository postRepository){
this.postRepository = postRepository;
}
public List<Post> getAllPosts(){
return postRepository.findAll();
}
public void insert(Post post) {
if(post.getBody() == null || post.getTitle() == null ){
throw new IllegalArgumentException("Missing args");
}
post.setDate(LocalDate.now());
postRepository.save(post);
}
public List<Post> getPostByUsername(User user){
return postRepository.findByCreatorId(user.getId());
}
}
The endpoint:
#GetMapping(value = "/posts")
public List<Post> posts(){
return postService.getAllPosts();
}
You should not expose your internal data model (JPA). Use transport classes. And you should remove the "#JsonProperty" from "public void setPassword(String password) ...". It is contradicting ("overriding") the "#JsonIgnore". And don't store your password as plaintext! Use for example jBCrypt.
My Setup:
public static class XUser {
private String username;
#JsonIgnore
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
//#JsonProperty
public void setPassword(String password) {
this.password = password;
}
}
#Test
public void testJson() {
XUser user = new XUser();
user.setPassword("oh shit!");
user.setUsername("name");
try {
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(user));
} catch (Exception ex) {
ex.printStackTrace();
}
}
And the output:
{"username":"name"}
Hi people I am working on one application .I have created a model but after giving all annotation and configuring all properties it is showing below error. Can anyone please look into below issue?
application.properties
spring.datasource.url = jdbc:mysql://localhost:3306/expenses
spring.datasource.username =dante
spring.datasource.password =jboss
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.open-in-view=false
spring.jpa.properties.hibernate.format_sql=true
server.port=9191
Main Class
package com.expenses.demo;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.expenses.demo.modal.Role;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
import com.expenses.service.UserService;
#SpringBootApplication
public class ExpenseApplication implements CommandLineRunner {
#Autowired
private UserService userService;
public static void main(String[] args) {
SpringApplication.run(ExpenseApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("Starting code");
User user = new User();
user.setFirstname("Aniket");
user.setLastname("Turiley");
user.setEmail("abc#gmail.com");
user.setPassword("abc");
user.setPhone("99220289");
Role role1=new Role();
role1.setRoleId(44L);
role1.setRoleName("ADMIN");
Set<UserRole> userRoleSet = new HashSet<>();
UserRole userRole = new UserRole();
userRole.setRole(role1);
userRole.setUser(user);
userRoleSet.add(userRole);
User user1= this.userService.createUser(user,userRoleSet);
System.out.println(user1.getUsername());
}
}
Model Class
Role.java
package com.expenses.demo.modal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="roleinformation")
public class Role {
#Id
private long roleId;
private String roleName;
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.LAZY,mappedBy = "role")
private Set<UserRole> userRoles = new HashSet<>();
public Role() {
}
public Role(int roleId, String roleName) {
this.roleId = roleId;
this.roleName = roleName;
}
public long getRoleId() {
return roleId;
}
public void setRoleId(long l) {
this.roleId = l;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
User.java
package com.expenses.demo.modal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="usersinfo")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
private String username;
private String password;
private String email;
private String phone;
private boolean enable=true;
// user has many roles
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER,mappedBy = "user")
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
public User() {
}
public User(Long id, String firstname, String lastname, String username, String password, String email,
String phone, boolean enable) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
this.enable = enable;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
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 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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
Repository Interfaces
RoleRepository
package com.expenses.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.expenses.demo.modal.Role;
public interface RoleRepository extends JpaRepository<Role, Long>{
}
UserRepository
package com.expenses.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.expenses.demo.modal.User;
public interface UserRepository extends JpaRepository<User, Long> {
public User findByUsername(String username);
}
Service Class
Service.java
package com.expenses.service;
import java.util.Set;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
public interface UserService {
//creating user
public User createUser(User user,Set<UserRole> userRoles) throws Exception;
}
Service Implementation class
ServiceImplementation.java
package com.expenses.service;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.expenses.demo.modal.User;
import com.expenses.demo.modal.UserRole;
import com.expenses.repository.RoleRepository;
import com.expenses.repository.UserRepository;
import com.expenses.service.UserService;
#Service
public class UserServiceImplementation implements UserService{
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Override
public User createUser(User user, Set<UserRole> userRoles) throws Exception{
User local= this.userRepository.findByUsername(user.getUsername());
if(local!=null) {
System.out.println("User Already Exist");
throw new Exception("User Already Exist");
}else {
// user create
for(UserRole ur:userRoles) {
roleRepository.save(ur.getRole());
}
user.getUserRoles().addAll(userRoles);
local = this.userRepository.save(user);
}
return local;
}
}
ERROR
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
[2m2021-07-28 18:16:59.304[0;39m [31mERROR[0;39m [35m8492[0;39m [2m---[0;39m [2m[ restartedMain][0;39m [36mo.s.b.d.LoggingFailureAnalysisReporter [0;39m [2m:[0;39m
***************************
APPLICATION FAILED TO START
***************************
Description:
Field userService in com.expenses.demo.ExpenseApplication required a bean of type 'com.expenses.service.UserService' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.expenses.service.UserService' in your configuration.
Spring Boot will do the component scan (search for Classes with #Service, #Repository, #Controller, #Component) annotation only classes that are located in the same package as the main class (#SpringBootApplication annoteted class), and its subpackages.
So you need eighter to
move ExpenseApplication one package up, to com.expenses,
move all classes that needs to be found by the component scan to to com.expenses.demo or a subpackage, or
configure the component scan (and Spring Data too), for example, by #SpringBootApplication(scanBasePackages = "com.expenses")
BTW: Najeeb Arif is right too, in addition you need to add #Autowired to UserServiceImplementation.userRepository but I think you do not need to add the #Repository annotation to the Spring-Data-JPA repository interfaces.
Add this to your main class
#SpringBootApplication(scanBasePackages = "com.expenses")
This will help the component scan will find your classes.
First mark both of your Repositories with
#Repository
In your user service, you are missing the Autowired annotation.
I personally like the constructor injection.
Role Repository
#Repository
public interface RoleRepository extends JpaRepository<Role, Long>{
}
Same for the user repo.
in your User Service Impl
#Service
public class UserServiceImplementation implements UserService{
private final UserRepository userRepository;
private final RoleRepository roleRepository;
/* when using constructor injection #Autowired is not required */
public UserServiceImplementation(UserRepository userRepository, RoleRepository roleRepository){
this.userRepository = userRepository;
this.roleRepository = roleRepository;
}
#Override
public User createUser(User user, Set<UserRole> userRoles) throws Exception{
//...
}
}
I tried to add One To Many Annotation to my spring boot project, but when I run my project I get "Failed to execute CommandLineRunner " error.
I wanted users in the user's table to have more than one city. So, I tried to add OneToMany Annotation.
You can see the error at the attachment.
User Class
package io.javabrains.springsecurity.jpa.models;
import com.spring.weather.*;
import java.util.*;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="app_user")
public class User {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int id;
private String userName;
private String password;
private boolean active;
private String role;
private String city;
#OneToMany(targetEntity = UserCity.class,cascade = CascadeType.ALL)
#JoinTable(name="USER_CITY",joinColumns=#JoinColumn(name="m_user_id"),
inverseJoinColumns=#JoinColumn(name="cityId"))
private List<UserCity> usercity;
public User() {
super();
// TODO Auto-generated constructor stub
}
public List<UserCity> getUsercity() {
return usercity;
}
public void setUsercity(List<UserCity> usercity) {
this.usercity = usercity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
User City Class
package io.javabrains.springsecurity.jpa.models;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="user_city")
public class UserCity {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
private int cityId;
private String cityName;
public UserCity() {
super();
// TODO Auto-generated constructor stub
}
public UserCity(int cityId, String cityName, User mUser) {
super();
this.cityId = cityId;
this.cityName = cityName;
this.mUser = mUser;
}
#ManyToOne
private User mUser;
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public User getmUser() {
return mUser;
}
public void setmUser(User mUser) {
this.mUser = mUser;
}
}
User Repository
package io.javabrains.springsecurity.jpa;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import io.javabrains.springsecurity.jpa.models.User;
public interface UserRepository extends JpaRepository<User, Integer> {
Optional<User> findByUserName(String userName);
}
User City Repository
package io.javabrains.springsecurity.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
public interface CityRepository extends JpaRepository<UserCity,id>{
}
Spring Application Class
package io.javabrains.springsecurity.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.spring.weather.WeatherService;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
#SpringBootApplication
#EnableJpaRepositories(basePackageClasses = UserRepository.class)
public class SpringsecurityApplication implements CommandLineRunner{
#Bean
public WeatherService ws() {
return new WeatherService ();
}
#Autowired
UserRepository userRepository;
CityRepository cityRepository;
public static void main(String[] args) {
SpringApplication.run(SpringsecurityApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("Application Running.");
User adminUser= new User();
UserCity ucity=new UserCity();
UserCity ucity2=new UserCity();
ucity.setCityName("amsterdam");
adminUser.setUserName("Admin");
adminUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
adminUser.setRole("ROLE_ADMIN");
adminUser.setActive(true);
adminUser.setCity("bologna");
ucity.setmUser(adminUser);
userRepository.save(adminUser);
cityRepository.save(ucity);
User newUser= new User();
newUser.setUserName("User");
newUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
newUser.setRole("ROLE_USER");
newUser.setActive(true);
newUser.setCity("maribor");
ucity2.setmUser(newUser);
userRepository.save(newUser);
cityRepository.save(ucity2);
}
}
The problem you are encountering, more specifically the NullPointerException at line 54 of your main application, is caused by the fact that the cityRepository is not
instantiated.
Looking through your configuration, I see that you only register the UserRepository with the #EnableJpaRepositories annotation.
Try adding also the CityRepository to the #EnableJpaRepositories, and also specify this bean as a candidate for autowiring( also add #Autowired to this bean, as you did for UserRepository)
For a good practice, following the MVC structure, it would be nice is all your spring repositories, the beans responsible for all CRUD operations with the database to be under the same package
I am trying to build a Spring Boot application that uses 2 data sources. My primary database for now is the in-memory database (just for testing purposes) with tables that are populated with the help of the sql file that I have created. The other database(oracledb) has tables that are already populated.
What am I trying to achieve?
I am trying to pull data from oracledb, process it and populate tables in h2 database.
What is the problem I am facing?
I only want the entities for the h2 db be created as tables in the in-mem database (I want to be able to specify h2 which entities to scan and create tables, not all the classes that have #Entity annotation). All of the classes that have #Entity are being created as tables in my in-mem database and that is what I am trying to avoid.
What have I tried?
I created two separate packages for the entities belonging to h2 and oracledb and using #EntityScan I only scanned the package that had entities for h2. This worked, however, I need the other entities for oracledb to be scanned so I am able to use them.
Code Snippet of what I have:
My applications.properties file
#spring.jpa.hibernate.ddl-auto=none
spring.jpa.generate-ddl=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2
# first data source
spring.datasource.url=jdbc:h2:mem:mydb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.application.name=Health Monitor
## 2nd data source
spring.production-datasource.url= jdbc:oracle://localhost:3306/db2
spring.production-datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.production-datasource.username=abcd
spring.production-datasource.password=xyz123
DemoApplication.java
package com.automation.demo;
import java.sql.SQLException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
#SpringBootApplication
//#EntityScan( basePackages = {"domain"} )
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean(initMethod = "start", destroyMethod = "stop")
public org.h2.tools.Server inMemoryH2DatabaseaServer() throws SQLException {
return org.h2.tools.Server.createTcpServer(
"-tcp", "-tcpAllowOthers", "-tcpPort", "9090");
}
}
ConfigureDB.java
package com.automation.demo.configurations;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.zaxxer.hikari.HikariDataSource;
#Configuration
public class ConfigureDB {
#Primary
#Bean
#ConfigurationProperties(prefix="spring.datasource")
public DataSourceProperties devDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#Primary
#ConfigurationProperties("spring.datasource.configuration")
public DataSource devDataSource() {
return devDataSourceProperties().initializeDataSourceBuilder()
.type(HikariDataSource.class).build();
}
#Bean
#ConfigurationProperties("spring.production-datasource")
public DataSourceProperties productionDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#ConfigurationProperties("spring.production-datasource.configuration")
public DataSource productionDataSource() {
return productionDataSourceProperties().initializeDataSourceBuilder()
.type(HikariDataSource.class).build();
}
}
Employee.java (for the h2 database)
package com.automation.demo.dev.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="test")
public class Employee {
// define fields
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
private int id;
#Column(name="FirstName")
private String firstName;
#Column(name="LastName")
private String lastName;
#Column(name="Email")
private String email;
// define constructors
public Employee() {
}
public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// define getter/setter
public int getId() {
return id;
}
public void setId(int 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;
}
// define tostring
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
CustomerInfo.java (this is the entity representing a table in oracledb, I want to prevent a table representing this entity to be created in the h2 database)
package com.automation.demo.production.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class CustomerInfo {
// define fields
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
private int id;
#Column(name="FirstName")
private String firstName;
#Column(name="LastName")
private String lastName;
#Column(name="Email")
private String email;
// define constructors
public CustomerInfo() {
}
public CustomerInfo(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// define getter/setter
public int getId() {
return id;
}
public void setId(int 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;
}
// define tostring
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
Please let me know if I have missed anything. Also, if there are any other mistakes I have made but are not related to my current problem please mention those as well.
Thanks.
Hibernate has a way to do this with SchemaFilterProvider.
SchemaFilterProvider
public class MySchemaFilterProvider implements SchemaFilterProvider {
#Override
public SchemaFilter getCreateFilter() {
return MySchemaFilter.INSTANCE;
}
#Override
public SchemaFilter getDropFilter() {
return MySchemaFilter.INSTANCE;
}
#Override
public SchemaFilter getMigrateFilter() {
return MySchemaFilter.INSTANCE;
}
#Override
public SchemaFilter getValidateFilter() {
return MySchemaFilter.INSTANCE;
}
}
SchemaFilter
public class MySchemaFilter implements SchemaFilter {
public static final MySchemaFilter INSTANCE = new MySchemaFilter();
#Override
public boolean includeNamespace(Namespace namespace) {
return true;
}
#Override
public boolean includeTable(Table table) {
if (table.getName().equals("customer")) {
return false;
}
return true;
}
#Override
public boolean includeSequence(Sequence sequence) {
return true;
}
}
Spring property configuration
spring.jpa.properties.hibernate.hbm2ddl.schema_filter_provider=MySchemaFilterProvider
Note - With Springboot the property is: spring.jpa.properties.hibernate.hbm2ddl.schema_filter_provider=xxx
I want retrieve user email from MySql database table using spring boot.i used findByEmailAndPassword in controller but it retrieve null value for email.
Here is my Code
controller
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.JPARepository;
import com.example.demo.pojo.regisbean;
#Controller
public class registerController {
regisbean pp;
#RequestMapping(value = "/")
public String mm() {
System.out.println("I am in m1 method");
return "index";
}
#RequestMapping(value = { "/register", "home" })
public String m1() {
System.out.println("I am in mm method");
return "register";
}
#Autowired
JPARepository jpaRepository;
#PostMapping("/register")
public String regis(#ModelAttribute regisbean rb)
{
System.out.println("I m in regis method");
regisbean b=jpaRepository.save(rb);
if(b!=null)
return "index";
else
return "fail";
}
#RequestMapping(value= {"/login1","login2"})
public String m2() {
System.out.println("i m in m2()");
return "login";
}
#PostMapping("/login")
public String login(#ModelAttribute regisbean rx,Model m) {
System.out.println("I am in Login");
regisbean re=jpaRepository.findByEmailAndPassword(rx.getEmail(), rx.getPassword());
if(re!=null)
{
m.addAttribute("email",rx.getEmail());
m.addAttribute("password",rx.getPassword());
System.out.println("yes");
return "loginsuccess";
}
else
{
System.out.println(rx.getEmail());
System.out.println("failed");
return "register";
}
}
}
pojo class
package com.example.demo.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "pro")
public class regisbean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column
private String name;
#Column
private String email;
#Column
private String phonenumber;
#Column
private String password;
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 String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Repository
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.pojo.regisbean;
public interface JPARepository extends CrudRepository<regisbean, Integer> {
public regisbean findByEmailAndPassword(String email,String password);
}
I was able to get your code to work by inserting a row in the table:
INSERT INTO pro (
id
,email
,name
,password
,phonenumber
)
VALUES (
0
,'user#domain.com'
,'Jim'
,'secret'
,'123-123-1234'
)
Then changing:
public String login(#ModelAttribute regisbean rx,Model m) {
to:
public String login(#RequestBody RegisBean rx,Model m) {
and POSTing the following request body to the /login resource:
{
"email": "user#domain.com",
"password": "secret"
}
I didn't have to make any changes to your Repo. I suspect your attempt was failing because RegisBean was never being initialized with any values and so the repo was asked to find a record with a null email and a null password.