How to solve column id not found in springboot - java

I am trying to get registration details from user and added a logic in spring boot that if email is already exist then throw error. So, when I register with new mail springboot is working fine but when I try with existed mail it shows status 500 error from server. In server, the error is column id not found.
#Repository
#Transactional
public interface SessionHandlingRepository extends JpaRepository<SessionHandling, Integer>{
#Query(value="Select email from session_handling where email= :email",nativeQuery =true)
public SessionHandling findByEmailId(#Param("email")String email);
#Query(value="Select email, password from session_handling where email= :email AND password= :password",nativeQuery =true)
public SessionHandling findByEmailIdAndPassword(#Param("email")String email, #Param("password")String password);
}
Entity
#Entity
public class SessionHandling {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String email;
private String password;
private String cpassword;
public SessionHandling(int id, String name, String email, String password, String cpassword) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.cpassword = cpassword;
} //all getter and setter
Controller
#Autowired
private SessionHandlingService service;
#PostMapping("/register")
public SessionHandling addUser(#RequestBody SessionHandling registration) throws Exception {
String tempEmailId = registration.getEmail();
if(tempEmailId != null && !"".equals(tempEmailId)) {
SessionHandling UserObj = service.fetchUserByEmailId(tempEmailId);
if(UserObj != null) {
throw new Exception("user with " +tempEmailId+ "already exist");
}
}
SessionHandling UserObj = null;
UserObj = service.addUser(registration);
return UserObj;
}
Error
2022-06-11 11:28:39.677 ERROR 8032 --- [nio-9197-exec-1]
o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for
servlet [dispatcherServlet] in context with path [] threw exception
[Request processing failed; nested exception is
org.springframework.dao.InvalidDataAccessResourceUsageException: could
not execute query; SQL [Select email from session_handling where
email= ?]; nested exception is
org.hibernate.exception.SQLGrammarException: could not execute query]
with root cause
java.sql.SQLException: Column 'id' not found.

#Query(value="Select email from session_handling where email=
:email",nativeQuery =true) public SessionHandling
findByEmailId(#Param("email")String email);
As per the repository method declaration mentioned by you, the following change require to your Query in order to correct the issue. As per your code you want to return SessionHandling complete object to service class.
#Query(value="Select * from session_handling where email= :email",nativeQuery =true)

Related

How to write query in springboot?

I am making a project where when a user login he will get a mail otp.I have successfully made the login page and also I am sending otp to the user mail address. Now I also want to validate the otp for that I have already created a otp column in database. But I can't figure out how to store the generated otp in the table.
Here is my code.
EmailSenderService class :
public class EmailSenderService {
#Autowired
private JavaMailSender mailSender;
public void sendMail(String toEmail,
String subject,
String body) {
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom("growthgreek#gamil.com");
message.setTo(toEmail);
message.setText(body);
message.setSubject(subject);
mailSender.send(message);
System.out.println("message sent .....");
}
}
OtpEmailController Class:
#Controller
public class OtpEmailController {
#Autowired
private EmailSenderService emailService;
Random random = new Random(1000);
#PostMapping("/send-otp")
public String sendOtp(#RequestParam("email") String email) {
int otp = random.nextInt(999999);
String subject = "OTP from session-handling-proj By Harshit";
String toEmail = email;
String body = "<h1> OTP = " + otp + "</h1>";
this.emailService.sendMail(toEmail, subject, body);
return ("success");
}
Repository Class :
#Repository
#Transactional
public interface SessionHandlingRepository extends JpaRepository<SessionHandling, Integer>{
#Query(value="Select * from session_handling where email= :email",nativeQuery =true)
public SessionHandling findByEmailId(#Param("email")String email);
#Query(value="Select * from session_handling where email= :email AND password= :password",nativeQuery =true)
public SessionHandling findByEmailIdAndPassword(#Param("email")String email, #Param("password")String password);
}
Entity Class :
#Entity
public class SessionHandling {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String email;
private String password;
private String cpassword;
private static final long OTP_VALID_DURATION = 5 * 60 * 1000; // 5 minutes
#Column(name = "one_time_password")
private String oneTimePassword;
#Column(name = "otp_requested_time")
private Date otpRequestedTime;
Where and how to write the query for saving the otp in database?
You can do it with your repository, first inject the repository in your service :
#Autowired
private SessionHandlingRepository sessionHandlingRepository;
you can then create an instance of your entity at the desired location (add getter and setter to the entity first):
SessionHandling sessionHandling = new SessionHandling();
sessionHandling.setName("theName");
// call Other setters ...
you can use the following repository method to save the entity in the database :
sessionHandlingRepository.save(sessionHandling);

How to send data from the database to the front end

Tell me how to get all its data from the database correctly by login. I wrote a code that checks the presence of a given login in the database. Next, I need to return all related information with this login to the frontend. it can be his description, mail, phone number, second name.
authorization:
#PostMapping("login")
public ResponseEntity<?> login(#RequestBody AuthenticationRequestDto requestDto) {
try {
String username = requestDto.getUsername();
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, requestDto.getPassword()));
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User with username: " + username + " not found");
}
String token = jwtTokenProvider.createToken(username, user.getRoles());
return ResponseEntity.ok(new JwtUser(
token,
user.getId(),
user.getUsername(),
user.getSecondName(),
user.getPhone(),
user.getDescription(),
user.getEmail(),
user.getRoles()));
} catch (AuthenticationException e) {
throw new BadCredentialsException("Invalid username or password");
}
}
to create a user object:
```
public class JwtUser implements UserDetails {
private String token;
private final Long id;
private final String username;
private String secondName;
private String password;
private String phone;
private String description;
private String email;
private boolean active;
private Date lastPasswordResetDate;
private final Collection<? extends GrantedAuthority> authorities;
public JwtUser(Long id, String username, String secondName, String password, String phone, String description,
String email, boolean active, Date lastPasswordResetDate,
Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.secondName = secondName;
this.password = password;
this.phone = phone;
this.description = description;
this.email = email;
this.active = active;
this.lastPasswordResetDate = lastPasswordResetDate;
this.authorities = authorities;
}
public JwtUser(String token, Long id, String username, String secondName, String phone, String description,
String email, Collection<? extends GrantedAuthority> authorities) {
this.token=token;
this.id = id;
this.username = username;
this.secondName = secondName;
this.phone = phone;
this.description = description;
this.email = email;
this.authorities = authorities;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
#JsonIgnore
public Long getId() {
return id;
}
public String getSecondName() {
return secondName;
}
public String getPhone() {
return phone;
}
public String getDescription() {
return description;
}
public String getEmail() {
return email;
}
public boolean isActive() {
return active;
}
#JsonIgnore
public Date getLastPasswordResetDate() {
return lastPasswordResetDate;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
#JsonIgnore
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#JsonIgnore
#Override
public boolean isAccountNonExpired() {
return true;
}
#JsonIgnore
#Override
public boolean isAccountNonLocked() {
return true;
}
#JsonIgnore
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
database:
public interface UserRepository extends JpaRepository<User, Long>{
User findByUsername(String name);
}
```
the authorization code is incorrect, since the constructor that collects the object to send it to the frontend does not understand what values to set. How to create an object using an authorized login?
UPDATE:
java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [db/migration/V1__Init_DB.sql]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1384) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1037) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.flywaydb.core.internal.resource.classpath.ClassPathResource.getUrl(ClassPathResource.java:83) ~[flyway-core-7.7.3.jar:na]
at org.flywaydb.core.internal.resource.classpath.ClassPathResource.getAbsolutePathOnDisk(ClassPathResource.java:72) ~[flyway-core-7.7.3.jar:na]
at org.flywaydb.core.internal.sqlscript.FlywaySqlScriptException.getMessage(FlywaySqlScriptException.java:81) ~[flyway-core-7.7.3.jar:na]
at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:54) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.spi.ThrowableProxy.<init>(ThrowableProxy.java:60) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.spi.LoggingEvent.<init>(LoggingEvent.java:119) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.Logger.buildLoggingEventAndAppend(Logger.java:419) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.Logger.filterAndLog_0_Or3Plus(Logger.java:383) ~[logback-classic-1.2.3.jar:na]
at ch.qos.logback.classic.Logger.log(Logger.java:765) ~[logback-classic-1.2.3.jar:na]
at org.apache.commons.logging.LogAdapter$Slf4jLocationAwareLog.error(LogAdapter.java:433) ~[spring-jcl-5.3.8.jar:5.3.8]
at org.springframework.boot.SpringApplication.reportFailure(SpringApplication.java:843) ~[spring-boot-2.5.1.jar:2.5.1]
at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:808) ~[spring-boot-2.5.1.jar:2.5.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:348) ~[spring-boot-2.5.1.jar:2.5.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.1.jar:2.5.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.1.jar:2.5.1]
at com.creamsa.springboot.SpringBootCreamsaApplication.main(SpringBootCreamsaApplication.java:10) ~[classes/:na]
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.session.JdbcSessionConfiguration$SpringBootJdbcHttpSessionConfiguration': Unsatisfied dependency expressed through method 'setTransactionManager' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateException:
Migration V1__Init_DB.sql failed
--------------------------------
SQL State : 42601
Error Code : 0
Message : ERROR: syntax error (approximate position: "create")
Position: 77
Location : db/migration/V1__Init_DB.sql (D:\prog\Eclipse\spring-boot-app\target\classes\db\migration\V1__Init_DB.sql)
Line : 2
Statement : create table user_role
(
user_id int8 not null,
roles varchar (255)
)
create table usr
(
id int8 generated by default as identity not null,
created timestamp,
updated timestamp,
active boolean,
seconde_name varchar (255),
description varchar (2048),
email varchar (50),
password varchar (40),
phone varchar (12),
username varchar (40),
primary key (id)
)
alter table if exists usr
add constraint UK_username unique (username)
alter table if exists usr
add constraint UK_email unique (email)
alter table if exists usr
add constraint UK_phone unique (phone)
alter table if exists user_role
add constraint FK_user_id_role foreign key (user_id) references usr
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:610)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1380)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1300)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.resolveMethodArguments(AutowiredAnnotationBeanPostProcessor.java:760)
77 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flywayInitializer' defined in class path resource [org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]: Invocation of init method failed; nested exception is org.flywaydb.core.internal.command.DbMigrate$FlywayMigrateException:
Migration V1__Init_DB.sql failed
--------------------------------
SQL State : 42601
Error Code : 0
Message : ERROR: syntax error (approximate position: "create")
Position: 77
Location : db/migration/V1__Init_DB.sql (D:\prog\Eclipse\spring-boot-app\target\classes\db\migration\V1__Init_DB.sql)
Line : 2
Statement : create table user_role
(
user_id int8 not null,
roles varchar (255)
)
create table usr
(
id int8 generated by default as identity not null,
created timestamp,
updated timestamp,
active boolean,
seconde_name varchar (255),
description varchar (2048),
email varchar (50),
password varchar (40),
phone varchar (12),
username varchar (40),
primary key (id)
)
alter table if exists usr
add constraint UK_username unique (username)
alter table if exists usr
add constraint UK_email unique (email)
alter table if exists usr
add constraint UK_phone unique (phone)
alter table if exists user_role
add constraint FK_user_id_role foreign key (user_id) references usr
at org.flywaydb.core.internal.command.DbMigrate.doMigrateGroup(DbMigrate.java:427)
at org.flywaydb.core.internal.command.DbMigrate.access$200(DbMigrate.java:56)
at org.flywaydb.core.internal.command.DbMigrate$3.call(DbMigrate.java:331)
at org.flywaydb.core.internal.jdbc.TransactionalExecutionTemplate.execute(TransactionalExecutionTemplate.java:66)
at org.flywaydb.core.internal.command.DbMigrate.applyMigrations(DbMigrate.java:328)
at org.flywaydb.core.internal.command.DbMigrate.migrateGroup(DbMigrate.java:291)
at org.flywaydb.core.internal.command.DbMigrate.access$100(DbMigrate.java:56)
at org.flywaydb.core.internal.command.DbMigrate$2.call(DbMigrate.java:195)
at org.flywaydb.core.internal.command.DbMigrate$2.call(DbMigrate.java:192)
at org.flywaydb.core.internal.database.postgresql.PostgreSQLAdvisoryLockTemplate.execute(PostgreSQLAdvisoryLockTemplate.java:69)
at org.flywaydb.core.internal.database.postgresql.PostgreSQLConnection.lock(PostgreSQLConnection.java:99)
at org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory.lock(JdbcTableSchemaHistory.java:141)
at org.flywaydb.core.internal.command.DbMigrate.migrateAll(DbMigrate.java:192)
at org.flywaydb.core.internal.command.DbMigrate.migrate(DbMigrate.java:152)
at org.flywaydb.core.Flyway$1.execute(Flyway.java:216)
at org.flywaydb.core.Flyway$1.execute(Flyway.java:165)
at org.flywaydb.core.Flyway.execute(Flyway.java:572)
at org.flywaydb.core.Flyway.migrate(Flyway.java:165)
at org.springframework.boot.autoconfigure.flyway.FlywayMigrationInitializer.afterPropertiesSet(FlywayMigrationInitializer.java:66)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1845)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782)
104 more
Exception: java.lang.IllegalStateException thrown from the UncaughtExceptionHandler in thread "main"
As previously mentioned from the .properties file I can see that you're missing the flyway configuration. You might need to add it
For a detailed configuration you can have a look at
https://baeldung.com/database-migrations-with-flyway
Anyways to temporarily diasble flyway you can just add the property
spring.flyway.enabled=false

NumberFormatting exception for bigint

I am using database as postgresql, connecting to the database with spring jdbctemplate.
The phone column in database is phone bigint The spring is throwing the java.lang.NumberFormatException
public UserDetails getUserDetails(int phone) {
String sql = "SELECT * FROM users where phone = ?";
UserDetails users = (UserDetails) jdbcTemplate.query(sql,new Object[]{phone},
new BeanPropertyRowMapper<UserDetails>(UserDetails.class));
return users;
}
**Error:-**
> For input string: "7894561230"; nested exception is
> java.lang.NumberFormatException: For input string: "7894561230"
My Bean is :-
public class UserDetails {
private int userId;
private String name;
private String email;
private String phone;
}
You problem is with int.
In Java int can hold any whole number from -2147483648 to 2147483647 and your value 7894561230 is out of range for it. So use long in place of int.

How to save token in database

I have a class User with:
int id;
String username;
String password;
String token;
Date tokenExpires;
And i have a method like this:
private EntityManager em;
private User authenticate(String username, String password) throws Exception {
// Authenticate against a database, LDAP, file or whatever
// Throw an Exception if the credentials are invalid
Query query = em.createQuery("Select u from User u WHERE u.username = :name and u.password = :password");
query.setParameter("name", username);
query.setParameter("password", password);
return (User) query.getSingleResult();
}
and a method to generate a token:
private String issueToken(String username) {
Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);
return token;
}
how to save this token to db, everytime user log in? so when user log in should generate a token, if user log in again it should generate a new token
When a user logs in, simply fetch the user from the database, then set the mentioned fields, the token and its' expiration date:
public User updateUser(String username, String password) {
User user = getUserBy(username, password);
String token = issueToken();
// token expires in 30 mins;
Date tokenExpires = new Date(System.currentTimeMillis() + 1800000);
user.setToken(token);
user.setTokenExpires(tokenExpires);
entityManager.getTransaction().begin();
entityManager.merge(user);
entityManager.getTransaction().commit();
}
Considering you are using Hibernate, then, the User model has to be annotated as well:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String token;
#Temporal(TemporalType.TIMESTAMP)
private Date tokenExpires;
// getters and setters, make sure they are present
}
if you use spring, try this guide, for example: https://javadeveloperzone.com/spring-boot/spring-boot-oauth2-jdbc-token-store-example/

Jdbc returns empty list but SQL query succesfully gets data [Spring]

I am trying to execute this query:
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql,new UserInfoMapper(),id);
return list.get(0);
}
but jdbc return empty list and I get exception at return line.
But if try to execute directly though the console it returns:
Query, Answer
Query was executed with id 1 and retured correct anwser;
But in method its returned this
I couldn't find any same questions so that may be point at my inattention to something. But I can't see any problem that may cause this. Thanks in advance;
Updated 1
Changing code to
#Override
public UserInfo get(Long id) {
String sql = "SELECT * FROM users WHERE id = ? ";
List<UserInfo> list = jdbcTemplate.query(sql, new Object[] {id},new UserInfoMapper());
return list.get(0);
}
resulted in same: result
Updated 2
#Override
public UserInfo mapRow(ResultSet resultSet, int i) throws SQLException {
UserInfo info = new UserInfo();
info.setId(resultSet.getLong("id"));
info.setFirstname(resultSet.getString("firstname"));
info.setMiddlename(resultSet.getString("middlename"));
info.setLastname(resultSet.getString("lastname"));
info.setUsername(resultSet.getString("username"));
info.setPassword(resultSet.getString("password"));
info.setEmail(resultSet.getString("email"));
info.setMobilephone(resultSet.getString("mobilephone"));
info.setPosition(resultSet.getString("position"));
return info;
}
public class UserInfo {
private Long id;
private String firstname;
private String middlename;
private String lastname;
private String username;
private String password;
private String email;
private String mobilephone;
private String position;
public UserInfo() {
}
}
Getter and setters for each field is there but I think there is no need to show them up.
Check user credentials that you are using to connect database from your application and the user credentials in console. And also check owner schema , table owner schema in your application.

Categories