SQLGrammarException: could not execute statement (PostgreSQL + Hibernate) - java

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 {
}

Related

How to return a message to HTTP request in Java?

I am creating an API to simulate a vending machine and I'm using Spring, JPA and MySQL. I have an endpoint for a POST request that allows for new user creation by entering the user's details into a table called users. I have a check to see if the username already exists in the table and if it does, I want to return a message that says the creation of a new user was unsuccessful because that username is already in use. If the user name is not in the table, I want to return the User object.
How do I return this error message? From what I have found so far, suggestions include the usage of ResponseEntity or creating a custom exception handler which all seemed overly complicated for something that I feel is quite straightforward. Is there an easier way to do this?
So this is what I want the response to look like when a new user has been created successfully (which I have currently managed to get working successfully):
{
"username": "user",
"password": "password",
"role": "BUYER",
"deposit": 0.0,
"id": 12
}
And if it fails, I want it to return something that looks along the lines of:
Error: username already in use.
or:
{
"error" : "Username already in use"
}
User object:
#Entity
#Table(name = "users")
public class User
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int userId;
#NotNull
#Column(name = "username", unique = true)
private String username;
#NotNull
#Column(name = "password")
private String password;
#NotNull
#Column(name = "role")
private Role role;
#NotNull
#Column(name = "deposit")
private BigDecimal deposit;
public User() {}
public User(String username, String password, Role role, BigDecimal deposit)
{
this.username = username;
this.password = password;
this.role = role;
this.deposit = deposit;
}
public int getId()
{
return userId;
}
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 Role getRole()
{
return role;
}
public void setRole(String role)
{
this.role = Role.valueOf(role);
}
public void setRole(Role role) {
this.role = role;
}
public BigDecimal getDeposit()
{
return deposit;
}
public void setDeposit(BigDecimal deposit)
{
this.deposit = deposit;
}
}
Method in the controller that is being called:
#PostMapping(value = "/create-user", consumes = {"application/json"})
public User createUser(#RequestBody User user)
{
return userService.createUser(user);
}
createUser method in UserService:
public User createUser(User user)
{
// if(userRepository.userExists(user.getUsername()) == 0)
return userRepository.save(user);
}
UserRepository is an interface that extends JpaRepository.
If I have missed some information or have worded the question incorrectly, please let me know and I'll update accordingly.
This can be achieved in multiple ways.
You can use JpaRepository's existsById() or similar "exists" methods. This would return a boolean. If it's true, that is if the entry already exists for a given id, you can send an error response. Otherwise, new user object. For that, you can have a model class something like UserOrError which will either hold a user object or an error string at a time. Use #JsonView annotation from Jackson library to show/ hide the fields. Read more
Based on the result of the above "exists" method, wrap it with ResponseEntity<T>. The return type of your controller method should be ResponseEntity<T>. Here's the link. The advantage of this method is that you can send different HTTP status codes
Throw a custom RuntimeException in your service layer and use Spring's exception handling like the RestControllerAdvice annotation

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

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.

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.

Using #IdClass for storing entity with composite primary key, but fails to persist

my id class as follows,
public class EmployeeId implements Serializable{
public EmployeeId(){}
public EmployeeId(Integer id, String country){
this.id = id;
this.country = country;
}
private Integer id;
private String country;
#Override
public int hashCode(){
return this.getCountry().hashCode() + getId();
}
#Override
public boolean equals(Object o){
boolean flag = false;
EmployeeId myId = (EmployeeId) o;
if((o instanceof EmployeeId)
&& (this.getCountry().equals(myId.getCountry()))
&& (this.id == myId.getId())){
flag = true;
}
return flag;
}
// rest of the code with getters only
}
Following is my entity using
#Entity
#IdClass(EmployeeId.class)
#Table(name="TBL_EMPLOYEE_FOUR")
public class EmployeeEntityTwo {
public EmployeeEntityTwo(){}
public EmployeeEntityTwo(Integer id,String country, String empName){
this.country = country;
this.employeeId = id;
this.empName = empName;
}
#Id
#Column(name="ID")
private Integer employeeId;
#Id
#Column(name="COUNTRY",length=50)
private String country;
#Column(name="NAME",length=50)
private String empName;
// getters and setters
}
This is my table
create table TBL_EMPLOYEE_FOUR(
ID integer,
COUNTRY varchar(50),
NAME varchar(50),
constraint PK_EMP_00239 primary key(ID,COUNTRY)
)
This is what i am trying to run
private static void idClassStore(EntityManager em) throws Exception{
List<EmployeeEntityTwo> employees = Arrays.asList(new EmployeeEntityTwo(12, "KENYA", "Ridushi Ogambe"),
new EmployeeEntityTwo(13, "GHANA", "Mikila Hanza"),
new EmployeeEntityTwo(14, "EGYPT", "Abdul Hameed Fagdaul"),
new EmployeeEntityTwo(15, "MOROCCO", "Jamil Mahmoud"),
new EmployeeEntityTwo(16, "LIBERIA", "Robert Damus"));
for(EmployeeEntityTwo employee : employees){
em.persist(employee);
}
}
But i get an exception as
Caused by: org.hibernate.AnnotationException: Property of #IdClass not found in entity com.entities.EmployeeEntityTwo: id
I am using JPA with Hibernate as persistence provider,
But #IdClass which i have used is of import javax.persistence.IdClass;
so where is am going wrong,
I have discovered the solution:
The 'id' field in the classes EmployeeEntityTwo and EmployeeId should be same.
// EmployeeId.java;
private Integer id;
should be
// EmployeeId.java;
private Integer employeeId;
I adjusted the getter respectively, and it worked.
From javax.persistence.IdClass JavaDocs:
The names of the fields or properties in the primary key class and the primary key fields or properties of the entity must correspond and their types must be the same.

Categories