How to send data from the database to the front end - java

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

Related

Java Spring JDBC. PSQLException: Use setObject() with an explicit Types value to specify the type to use

I'm trying to create a new user and receive the following error:
ERROR 16444 --- [nio-8080-exec-2] 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.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [INSERT INTO users (name, surname, year_of_birth, email, password, position_id) VALUES (:name, :surname, :year_of_birth, :email, :password, (SELECT id FROM positions WHERE name = :position))]; nested exception is org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of org.springframework.jdbc.core.namedparam.MapSqlParameterSource. Use setObject() with an explicit Types value to specify the type to use.] with root cause
org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of org.springframework.jdbc.core.namedparam.MapSqlParameterSource. Use setObject() with an explicit Types value to specify the type to use.
Here is my Controller:
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public String create(Model model, #RequestParam Map<String, Object> parameters) {
UserDto userDto = new UserDto();
setParametersForUser(userDto, parameters);
model.addAttribute("user", userService.createUser(userDto));
return "user";
}
private void setParametersForUser(UserDto userDto, Map<String, Object> parameters) {
userDto.setName(parameters.get("name").toString());
userDto.setSurname(parameters.get("surname").toString());
userDto.setYearOfBirth(Integer.valueOf(parameters.get("year_of_birth").toString()));
userDto.setEmail(parameters.get("email").toString());
userDto.setPassword(parameters.get("password").toString());
userDto.setPositionDto(UserDto.PositionDto.valueOf(parameters.get("position").toString()));
}
Here is my Service:
#Override
public UserDto createUser(UserDto userDto) {
User newUser = userDao.createUser(toUser(userDto));
return toDto(newUser);
}
private User toUser(UserDto userDto) {
User user = new User();
user.setId(userDto.getId());
user.setName(userDto.getName());
user.setSurname(userDto.getSurname());
user.setYearOfBirth(userDto.getYearOfBirth());
user.setEmail(userDto.getEmail());
user.setPassword(userDto.getPassword());
user.setPosition(User.Position.valueOf(userDto.getPositionDto().toString()));
return user;
}
private UserDto toDto(User entity) {
UserDto dto = new UserDto();
dto.setId(entity.getId());
dto.setName(entity.getName());
dto.setSurname(entity.getSurname());
dto.setYearOfBirth(entity.getYearOfBirth());
dto.setEmail(entity.getEmail());
dto.setPassword(entity.getPassword());
dto.setPositionDto(UserDto.PositionDto.valueOf(entity.getPosition().toString()));
return dto;
}
Here is Dao:
private static final String INSERT = "INSERT INTO users (name, surname, year_of_birth, email, password, position_id) VALUES (:name, :surname, :year_of_birth, :email, :password, (SELECT id FROM positions WHERE name = : position))";
#Override
public User createUser(User user) {
KeyHolder keyHolder = new GeneratedKeyHolder();
Map<String, Object> parameters = getParameters(user);
SqlParameterSource source = new MapSqlParameterSource(parameters);
int rowsUpdated = template.update(INSERT, source, keyHolder, new String[]{"id"}); //mistake is here
if (rowsUpdated != 1) {
throw new RuntimeException("Can't create user");
}
Long id = Optional.ofNullable(keyHolder.getKey()).map(Number::longValue).orElseThrow(() -> new RuntimeException("Can't create user"));
return getUserById(id);
}
private Map<String, Object> getParameters(User user) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("name", user.getName());
parameters.put("surname", user.getSurname());
parameters.put("year_of_birth", user.getYearOfBirth().toString());
parameters.put("email", user.getEmail());
parameters.put("password", user.getPassword());
parameters.put("position", user.getPosition().toString());
return parameters;
}
User must be as follows:
public class User
private Long id;
private String name;
private String surname;
private Integer yearOfBirth;
private String email;
private String password;
private Position position;
public enum Position {
CEO,
MANAGER,
WORKER
}
And tables in PostgreSQL:
CREATE TABLE positions (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(100)
)
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
surname VARCHAR(100) NOT NULL,
year_of_birth INTEGER,
email VARCHAR(100) NOT NULL,
password VARCHAR(20) NOT NULL,
position_id BIGINT REFERENCES positions,
deleted BOOLEAN DEFAULT false NOT NULL
)
INSERT INTO positions (name)
VALUES ('CEO'),
('MANAGER'),
('WORKER');
INSERT INTO users (name, surname, year_of_birth, email, password, position_id)
VALUES ('Tom','Ands',1999,'Tom#ggg.com','R887h24hs',(SELECT id FROM positions WHERE name = 'WORKER'));
Where can be the problem? Pls help

How to solve column id not found in springboot

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)

unconfigured columnfamily error during insert

I have the following user info object mapped to a table "user_info" in my keyspace "data_collection". I have created the "user_info" table in my cassandra database. I am using spring data cassandra for connecting to cassandra database from JAVA and the spring annotations as below.
#Table(name="user_info",keyspace="data_collection", caseSensitiveKeyspace = false,caseSensitiveTable = false)
public class UserInfo {
#PartitionKey
private UUID id;
#PrimaryKeyColumn
private String email;
private int phone;
private String name;
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 getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
}
I am using the following code to insert a record into my "user_info" table.
#Autowired
CassandraTemplate cassandraTemplate;
public void saveUserInfo(UserInfo userInfo){
logger.debug("userInfo "+new Gson().toJson(userInfo));
String email = userInfo.getEmail();
Select select = QueryBuilder.select().from("user_info");
select.where(QueryBuilder.eq("email", email));
logger.debug("Query "+select.toString());
UserInfo existingUser = cassandraTemplate.selectOne(select, UserInfo.class);
if(existingUser!=null){
cassandraTemplate.update(userInfo);
}
else{
cassandraTemplate.insert(userInfo);
}
}
My selectOne is working properly whereas during insert I am getting the following exception. I have clearly mapped the UserInfo.java class to the table name "user_info" using annotation above. I don't know why the insert is trying to happen to the table "userinfo".
org.springframework.cassandra.support.exception.CassandraInvalidQueryException: unconfigured columnfamily userinfo; nested exception is com.datastax.driver.core.exceptions.InvalidQueryException: unconfigured columnfamily userinfo
at org.springframework.cassandra.support.CassandraExceptionTranslator.translateExceptionIfPossible(CassandraExceptionTranslator.java:128)
at org.springframework.cassandra.core.CqlTemplate.potentiallyConvertRuntimeException(CqlTemplate.java:946)
at org.springframework.cassandra.core.CqlTemplate.translateExceptionIfPossible(CqlTemplate.java:930)
at org.springframework.cassandra.core.CqlTemplate.translateExceptionIfPossible(CqlTemplate.java:912)
at org.springframework.cassandra.core.CqlTemplate.doExecute(CqlTemplate.java:278)
at org.springframework.cassandra.core.CqlTemplate.doExecute(CqlTemplate.java:559)
at org.springframework.cassandra.core.CqlTemplate.execute(CqlTemplate.java:1333)
at org.springframework.data.cassandra.core.CassandraTemplate.doUpdate(CassandraTemplate.java:895)
at org.springframework.data.cassandra.core.CassandraTemplate.update(CassandraTemplate.java:537)
at org.springframework.data.cassandra.core.CassandraTemplate.update(CassandraTemplate.java:532)
Please find below the description of the table in cassandra.
CREATE TABLE user_info (
name text,
email text,
phone int
PRIMARY KEY ((email))
) WITH
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.100000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.000000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='99.0PERCENTILE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};
Quick update : I just tried saving another class Test.java. It was mapped to a table "test_info". I got the following error
org.springframework.cassandra.support.exception.CassandraInvalidQueryException: unconfigured columnfamily test; nested exception is com.datastax.driver.core.exceptions.InvalidQueryException: unconfigured columnfamily test
at org.springframework.cassandra.support.CassandraExceptionTranslator.translateExceptionIfPossible(CassandraExceptionTranslator.java:128)
at org.springframework.cassandra.core.CqlTemplate.potentiallyConvertRuntimeException(CqlTemplate.java:946)
at org.springframework.cassandra.core.CqlTemplate.translateExceptionIfPossible(CqlTemplate.java:930)
at org.springframework.cassandra.core.CqlTemplate.translateExceptionIfPossible(CqlTemplate.java:912)
at org.springframework.cassandra.core.CqlTemplate.doExecute(CqlTemplate.java:278)
at org.springframework.cassandra.core.CqlTemplate.doExecute(CqlTemplate.java:559)
at org.springframework.cassandra.core.CqlTemplate.execute(CqlTemplate.java:1323)
at org.springframework.data.cassandra.core.CassandraTemplate.doInsert(CassandraTemplate.java:708)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:290)
at org.springframework.data.cassandra.core.CassandraTemplate.insert(CassandraTemplate.java:285)
I am just wondering if my Java class name and the table name in cassandra should always be the same. Because its looking for the columnfamily "test" instead of "test_info" which I have specified in the #Table annotation.
Below is the description of my keyspace
CREATE KEYSPACE data_collection WITH replication = {
'class': 'SimpleStrategy',
'replication_factor': '3'
};
EDIT - SOLVED :
I found the solution based on the conversation with #pinkpanther.
I had imported com.datastax.driver.mapping.annotations.Table instead of org.springframework.data.cassandra.mapping.Table which is why it didn't honor the table name mapping. Thanks for your help.
The problem might be with the package import of Table, Spring Data Cassandra needs org.springframework.data.cassandra.mapping.Table. Replace the imported com.datastax.driver.mapping.annotations.Table with it.

SQLGrammarException: could not execute statement (PostgreSQL + Hibernate)

My DB contain User table with same named fields in class User.
I still have a problem with #Column annotation: Intellij IDEA stresses the name of the column.
DBTable
CREATE TABLE "user"
(
email character varying,
login character varying NOT NULL,
password character varying NOT NULL,
name character varying NOT NULL,
id_user numeric NOT NULL,
CONSTRAINT user_pkey PRIMARY KEY (login, password, id_user),
CONSTRAINT user_email_key UNIQUE (email)
)
Why this exception of syntax?? I have the same named table
root cause
org.postgresql.util.PSQLException: ERROR: syntax error at or near "User"
Position: 13
org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:365)
org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3067)
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3509)
org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:369)
org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:286)
org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:339)
org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234)
org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
com.classes.UserDB.registerUser(UserDB.java:17)
com.servlets.Registration.doPost(Registration.java:29)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
User class
package com.DB;
import javax.persistence.*;
#Entity
public class User {
#Lob
private String email;
#Lob
private String login;
#Lob
private String password;
#Lob
private String name;
#Id
#GeneratedValue
private int id_user;
public int getId_user() {
return id_user;
}
public void setId_user(int id_user) {
this.id_user = id_user;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUserFromBase(){
return this;
}
}
How it resolve?
user is a reserved word and table with name user can not be created.
try adding #Table(name="USER_TABLE") after #Entity to change table name.
sorry haven`t read that carefully. it seems u already have a table named "USER". that's the problem with oracle
"user" is a reserved word in PostgreSQL and it's usually not a good idea use reserved words for tables or columns.
If you want to save yourself a lot of trouble use a different name. users, user_acount.
also would change the class name for the same as table.
put #Table(name="USERS") annotation:
#Entity
#Table(name="users")
public class Users {
}

BasicPropertyAccessor:167 - IllegalArgumentException in class in Struts

I'm working on online exam project using struts spring and hibernate. While submitting the values from registration.jsp, i'm trying to insert those details in two different tables by using one table's primary key as foreign key in another table. But i could able to save only values in one table( says primary key table). But i could not able to save details in another table. In console log, i could see the follwing exception,
2013-09-17 18:16:39 INFO RegistrationAction:188 - Entering Into SaveUserDetails()
2013-09-17 18:16:39 INFO class:25 - Entering Into saveUserRegistration()
2013-09-17 18:16:39 INFO class:13 - Entering Into UserRegistrationDAO
Hibernate: insert into user_details (first_name, last_name, email, password, gender, dob, phone, experience) values (?, ?, ?, ?, ?, ?, ?, ?)
2013-09-17 18:16:39 INFO RegistrationAction:214 - Entering Into setUserAddress()
2013-09-17 18:16:39 INFO class:25 - Entering Into saveUserRegistration()
2013-09-17 18:16:39 INFO class:13 - Entering Into UserRegistrationDAO
2013-09-17 18:16:39 ERROR BasicPropertyAccessor:167 - IllegalArgumentException in class: onlineexam.beans.UserDetails, getter method of property: user_id
Sep 17, 2013 6:16:39 PM org.apache.catalina.core.ApplicationDispatcher invoke
RegistrationAction.java
public String SaveUserDetails() {
String forward = "success";
try {
logger.info("Entering Into SaveUserDetails()");//Log Information
UserDetails s = new UserDetails();
s.setFirst_name(getFirst_Name());
s.setLast_name(getLast_Name());
s.setEmail(getEmailid());
s.setPassword(getPassWord());
s.setGender(getGender());
s.setDob(getDateofbirth());
s.setPhone(getPhoneNo());
s.setExperience(getUser_experience());
userRegistrationService.saveUserRegistration(s);
Set<UserAddress> address = new HashSet<UserAddress>(0);
setUserAddress(address);
logger.info("SuccessFull:Exiting from SaveUserDetails()");//Log Information
} catch (Exception ex) {
forward = "error";
}
return forward;
}
public void setUserAddress(Set<UserAddress> address) throws Exception {
logger.info("Entering Into setUserAddress()");
UserAddress ad = new UserAddress();
ad.setAddr_line1(getAddr_line1());
ad.setAddr_line2(getAddr_line2());
ad.setAddr_line3(getAddr_line3());
ad.setCity(getCity());
ad.setZipcode(getZipcode());
ad.setState(getState());
ad.setCountry(getCountry());
address.add(ad);
userRegistrationService.saveUserRegistration(ad);
logger.info("SuccessFull:Exiting from setUserAddress()");//Log Information
}
}
UserRegistrationDAO.java
public class UserRegistrationDao extends HibernateDaoSupport {
private static Logger logger = Logger.getLogger("UserRegistrationDao.class");
public UserRegistrationDao() {}
public UserDetails saveUserRegistration(UserDetails s) throws Exception {
logger.info("Entering Into UserRegistrationDAO");
return (UserDetails)getHibernateTemplate().merge(s);
}
}
UserRegistrationService.java
public class UserRegistrationService {
private UserRegistrationDao userRegistrationDao;
private static Logger logger=Logger.getLogger("UserRegistrationService.class");
public void init() throws Exception {}
public UserRegistrationDao getUserRegistrationDao() {
logger.info("Entering into getUserRegistrationDao()");//Log information
return userRegistrationDao;
}
public void setUserRegistrationDao(UserRegistrationDao userRegistrationDao) {
this.userRegistrationDao = userRegistrationDao;
logger.info("Entering Into setUserRegistrationDao()");//Log Information
}
public UserDetails saveUserRegistration (UserDetails user) throws Exception {
logger.info("Entering Into saveUserRegistration()");//Log Information
return userRegistrationDao.saveUserRegistration(user);
}
}
UserDetails.java
public class UserDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#OneToMany (mappedBy="user_details")
private int user_id; //primary key
private String first_name;
private String last_name;
private String email;
private String password;
private String gender;
private int dob;
private int phone;
private float experience;
//getters and setters created
UserAddress.java
public class UserAddress extends UserDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int address_id; //primary key
#ManyToOne(fetch=FetchType.EAGER, targetEntity=UserDetails.class)
#JoinColumn(name="user_id")
private int user_id;
private String addr_line1;
private String addr_line2;
private String addr_line3;
private String city;
private int zipcode;
private String state;
private String country;
//getters and setters created
What are you doing in UserAddress doesn't constitute a many to one association from UserAddress to UserDetails. Your are only adding the user_id to UserDetails class.
What you have to do instead:
#ManyToOne(fetch=FetchType.EAGER, targetEntity=UserDetails.class)
#JoinColumn(name="user_id")
UserDetails userDetails;
public UserDetails getUserDetails() {
return userDetails;
}
public void setUserDetails() {
this.userDetails = userDetails;
}
I don't understand why UserAddress extends UserDetails? I recommend you to read more about hibernate associations.

Categories