I am trying to run hibernate on a PostgreSQL 8.4.2 DB. Whenever I try to run a simple java code like:
List<User> users = service.findAllUsers();
I get the following error:
PSQLException: ERROR: relation "TABLE_NAME" does not exist
Since I have option hibernate.show_sql option set to true, I can see that hibernate is trying to run the following SQL command:
select this_.USERNAME as USERNAME0_0_, this_.PASSWORD as PASSWORD0_0_
from "TABLE_NAME" this_
When in reality, it should at least run something like:
select this_."USERNAME" as USERNAME0_0_, this_."PASSWORD" as PASSWORD0_0_
from "SCHEMA_NAME"."TABLE_NAME" as this_
Does anyone know what changes I need to make for Hibernate to produce the right SQL for PostgreSQL?
I have set up the necessary postgreSQL datasource in applicationContext.xml file:
<!-- Use Spring annotations -->
<context:annotation-config />
<!-- postgreSQL datasource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url"
value="jdbc:postgresql://localhost/DB_NAME:5432/SCHEMA_NAME" />
<property name="username" value="postgres" />
<property name="password" value="password" />
<property name="defaultAutoCommit" value="false" />
</bean>
On the same file I have set up the session factory with PostgreSQL dialect:
<!-- Hibernate session factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.myPackage.dbEntities.domain.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- setup transaction manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
Finally, the way I am mapping the domain class to the table is:
@Entity
@Table(name = "`TABLE_NAME`")
public class User {
@Id
@Column(name = "USERNAME")
private String username;
Has anyone encountered a similar error?. Any help in solving this issue will be much appreciated.
Please note that question is different to post Cannot simply use PostgreSQL table name (”relation does not exist”)
Apologies for the lengthy post.
I am using Spring Boot with Hibernate, JPA and Postgresql database. I am trying to create new user and save it. I have the following code:
UserEntity.java
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Getter
@Setter
@Entity(name = "Users")
public class UserEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(nullable = false, unique = true)
private String userId;
@Column(nullable = false, length = 50)
private String firstName;
@Column(nullable = false, length = 50)
private String lastName;
@Column(nullable = false, length = 120, unique = true)
private String email;
@Column(nullable = false, unique = true)
private String encryptedPassword;
}
UserController.java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
UserService userService;
private static final ModelMapper modelMapper = new ModelMapper();
@PostMapping
public ResponseEntity<CreateUserResponseModel> createUser(@Valid @RequestBody CreateUserRequestModel userDetails){
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
UserDto userDto = modelMapper.map(userDetails, UserDto.class);
UserDto createdUser = userService.createUser(userDto);
CreateUserResponseModel returnValue = modelMapper.map(createdUser, CreateUserResponseModel.class);
return ResponseEntity.status(HttpStatus.CREATED).body(returnValue);
}
}
UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService{
private final UserRepository userRepository;
@Autowired
public UserServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
private static final ModelMapper modelMapper = new ModelMapper();
@Override
@Transactional
public UserDto createUser(UserDto user) {
user.setUserId(UUID.randomUUID().toString());
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
UserEntity userEntity = modelMapper.map(user, UserEntity.class);
userEntity.setEncryptedPassword("test");
userRepository.save(userEntity);
UserDto returnValue = modelMapper.map(userEntity, UserDto.class);
return returnValue;
}
}
UserRepository.java
public interface UserRepository extends CrudRepository<UserEntity, Long> {
}
Application.yaml
server:
port: 8080
spring:
datasource:
url: jdbc:postgresql://localhost:5432/userservices
username: postgres
password: user
jpa:
show-sql: true
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.PostgreSQL81Dialect
format_sql: true
jackson:
serialization:
fail-on-empty-beans: false
logging:
level:
org:
springframework: info
My error in Intelij looks like this:
org.postgresql.util.PSQLException: ERROR: relation "users" does not exist
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553) ~[postgresql-42.2.20.jar:42.2.20]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285) ~[postgresql-42.2.20.jar:42.2.20]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323) ~[postgresql-42.2.20.jar:42.2.20]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481) ~[postgresql-42.2.20.jar:42.2.20]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401) ~[postgresql-42.2.20.jar:42.2.20]
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164) ~[postgresql-42.2.20.jar:42.2.20]
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:130) ~[postgresql-42.2.20.jar:42.2.20]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-4.0.3.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-4.0.3.jar:na]
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:43) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3195) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3801) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:84) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:93) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:720) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:706) ~[hibernate-core-5.4.31.Final.jar:5.4.31.Final]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:362) ~[spring-orm-5.3.7.jar:5.3.7]
at jdk.proxy3/jdk.proxy3.$Proxy96.persist(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:311) ~[spring-orm-5.3.7.jar:5.3.7]
at jdk.proxy3/jdk.proxy3.$Proxy96.persist(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:597) ~[spring-data-jpa-2.5.1.jar:2.5.1]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:289) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:529) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:599) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:163) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138) ~[spring-data-commons-2.5.1.jar:2.5.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.7.jar:5.3.7]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.7.jar:5.3.7]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:174) ~[spring-data-jpa-2.5.1.jar:2.5.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.7.jar:5.3.7]
at jdk.proxy3/jdk.proxy3.$Proxy99.save(Unknown Source) ~[na:na]
at com.example.usermicroservice.service.UserServiceImpl.createUser(UserServiceImpl.java:34) ~[classes/:na]
at com.example.usermicroservice.service.UserServiceImpl$$FastClassBySpringCGLIB$$a58b43f0.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) ~[spring-core-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:779) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.7.jar:5.3.7]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.7.jar:5.3.7]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750) ~[spring-aop-5.3.7.jar:5.3.7]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692) ~[spring-aop-5.3.7.jar:5.3.7]
at com.example.usermicroservice.service.UserServiceImpl$$EnhancerBySpringCGLIB$$df5a5f72.createUser(<generated>) ~[classes/:na]
at com.example.usermicroservice.controller.UserController.createUser(UserController.java:39) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.7.jar:5.3.7]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.3.7.jar:5.3.7]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.46.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.7.jar:5.3.7]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.46.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.7.jar:5.3.7]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.7.jar:5.3.7]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.7.jar:5.3.7]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.7.jar:5.3.7]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at java.base/java.lang.Thread.run(Thread.java:831) ~[na:na]
I am testing it with Postman and sending JSON in body like this:
{
"firstName": "Anna",
"lastName": "Faranhay",
"email": "Faranhay@gmail.com",
"password": "ana1234"
}
But in Postman I am receiving 500 Internal Error.
Any advice appreciated.
The error message «org.postgresql.util.PSQLException: ERROR: relation «app_user» does not exist» indicates that there is a problem with accessing a table in a PostgreSQL database. It appears that the table in question, «app_user», is not present in the database. This can occur for a number of reasons, including issues with the database setup or connection, problems with the table creation query, or incorrect referencing of the table name in your Java code.
Method 1: Verify the Table Creation
To fix the error «org.postgresql.util.PSQLException: ERROR: relation ‘app_user’ does not exist» in Java, we can verify if the table exists in the PostgreSQL database. Here are the steps to do it:
- Connect to the database using Java JDBC driver. For example:
String url = "jdbc:postgresql://localhost:5432/mydatabase";
String user = "myuser";
String password = "mypassword";
Connection conn = DriverManager.getConnection(url, user, password);
- Query the database to get the list of tables. For example:
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getTables(null, null, null, new String[] {"TABLE"});
List<String> tables = new ArrayList<>();
while (rs.next()) {
String tableName = rs.getString("TABLE_NAME");
tables.add(tableName);
}
- Check if the table exists in the list of tables. For example:
if (tables.contains("app_user")) {
// Table exists
} else {
// Table does not exist
}
- If the table does not exist, create it using SQL commands. For example:
Statement stmt = conn.createStatement();
stmt.executeUpdate("CREATE TABLE app_user (id SERIAL PRIMARY KEY, username VARCHAR(50), password VARCHAR(50))");
- Close the database connection. For example:
With these steps, we can verify if the table exists in the PostgreSQL database and create it if it does not exist. This should fix the error «org.postgresql.util.PSQLException: ERROR: relation ‘app_user’ does not exist».
Method 2: Verify the Database Connection
To fix the org.postgresql.util.PSQLException: ERROR: relation "app_user" does not exist
error in Java, you can verify the database connection by following these steps:
- Check the database URL, username, and password in the
application.properties
orapplication.yml
file.
spring.datasource.url=jdbc:postgresql://localhost:5432/mydatabase
spring.datasource.username=myusername
spring.datasource.password=mypassword
- Verify that the PostgreSQL driver is added as a dependency in your
pom.xml
file.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.18</version>
</dependency>
-
Check if the
app_user
table exists in the database. You can use a SQL client like pgAdmin to verify this. -
Use the
JdbcTemplate
class to execute a simple SQL query to verify the database connection.
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
public class DatabaseVerifier {
private final JdbcTemplate jdbcTemplate;
public DatabaseVerifier(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void verify() {
String sql = "SELECT COUNT(*) FROM app_user";
int count = jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println("Number of app_user records: " + count);
}
}
- Call the
verify()
method to verify the database connection.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import javax.sql.DataSource;
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(MyApp.class, args);
DataSource dataSource = context.getBean(DataSource.class);
DatabaseVerifier verifier = new DatabaseVerifier(dataSource);
verifier.verify();
}
}
By following these steps, you should be able to verify the database connection and fix the org.postgresql.util.PSQLException: ERROR: relation "app_user" does not exist
error in Java.
Method 3: Check for Case Sensitivity Issues in Table Name
One common cause of the org.postgresql.util.PSQLException: ERROR: relation "app_user" does not exist
error is case sensitivity issues in the table name. Here are the steps to check for and fix these issues in Java:
- Check the case of the table name in your SQL query or code. Make sure it matches the actual case of the table name in the database.
String sql = "SELECT * FROM app_user"; // check the case of "app_user"
- If the case of the table name in your code matches the actual case of the table name in the database, check for any quotes or backticks around the table name. These can sometimes cause case sensitivity issues.
String sql = "SELECT * FROM \"App_User\""; // remove quotes around table name
- If the table name is still not found, try converting the table name to lowercase or uppercase in your SQL query or code.
String sql = "SELECT * FROM APP_USER"; // convert table name to uppercase
- Finally, make sure the table actually exists in the database. You can check this by running a separate SQL query or by using a database management tool.
String sql = "SELECT * FROM app_user"; // make sure "app_user" exists in the database
By following these steps, you should be able to fix the org.postgresql.util.PSQLException: ERROR: relation "app_user" does not exist
error caused by case sensitivity issues in the table name.
Method 4: Verify the Correct Schema is Being Used
To fix the org.postgresql.util.PSQLException: ERROR: relation "app_user" does not exist
error in Java, you can verify that the correct schema is being used. Here are the steps to do so:
-
Check the schema name in your PostgreSQL database. You can use the following SQL query to do so:
SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'your_schema_name';
-
Make sure that you are using the correct schema name in your Java code. You can do so by specifying the schema name in your JDBC connection URL, like this:
String url = "jdbc:postgresql://localhost:5432/your_database_name?currentSchema=your_schema_name"; Connection conn = DriverManager.getConnection(url, "username", "password");
-
If you are using Hibernate, you can specify the schema name in your
persistence.xml
file, like this:<property name="hibernate.default_schema" value="your_schema_name"/>
-
If you are using Spring Data JPA, you can specify the schema name in your
application.properties
file, like this:spring.datasource.url=jdbc:postgresql://localhost:5432/your_database_name?currentSchema=your_schema_name
By verifying the correct schema is being used, you should be able to fix the org.postgresql.util.PSQLException: ERROR: relation "app_user" does not exist
error in your Java application.
Method 5: Ensure Proper Table Name is Referenced in Java Code
To fix the org.postgresql.util.PSQLException: ERROR: relation "app_user" does not exist
error in Java, you can ensure that the proper table name is referenced in your Java code. Here are the steps to do so:
- Check the spelling of the table name in your Java code. Make sure that it matches the actual table name in the PostgreSQL database.
String tableName = "app_user"; // check if this matches the actual table name
- Use the correct schema name in your Java code. If your table is in a schema other than the default
public
schema, you need to specify the schema name in your Java code.
String schemaName = "my_schema"; // replace with the actual schema name
String tableName = "app_user";
// use the schema name in the SQL query
String sql = "SELECT * FROM " + schemaName + "." + tableName;
- Use double quotes around the table name if it contains uppercase letters or special characters.
String tableName = "\"App_User\""; // use double quotes around the table name
- Use prepared statements instead of concatenating strings to avoid SQL injection attacks and to ensure proper quoting of table names.
String schemaName = "my_schema"; // replace with the actual schema name
String tableName = "app_user";
// use a prepared statement with placeholders for the schema and table names
String sql = "SELECT * FROM ??.??";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, schemaName);
pstmt.setString(2, tableName);
ResultSet rs = pstmt.executeQuery();
By following these steps, you can ensure that the proper table name is referenced in your Java code and avoid the org.postgresql.util.PSQLException: ERROR: relation "app_user" does not exist
error.
Issue
I have an application that I’m using spring boot and postgres. I’m getting this error when I try to create a user.
When I run this query on my database, I get the same error:
select * from APP_USER
ERROR: relation "app_user" does not exist
LINE 1: select * from APP_USER
^
********** Error **********
ERROR: relation "app_user" does not exist
SQL state: 42P01
But if I change that to:
select * from "APP_USER"
It works.
How can I configure that on my spring boot app?
dependencies in pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-tiles2</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4-1201-jdbc41</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.properties:
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/boek
spring.datasource.username=postgres
spring.datasource.password=ABCD123$
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.generate-ddl=false
#spring.jpa.hibernate.ddl-auto=create
spring.jpa.show-sql=true
My entity:
@Entity
@Table(name = "APP_USER")
public class User implements Serializable {
private static final long serialVersionUID = -1152779434213289790L;
@Id
@Column(name="ID", nullable = false, updatable = false)
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@Column(name="NAME", nullable = false)
private String name;
@Column(name="USER_NAME", nullable = false, unique = true)
private String username;
@Column(name="PASSWORD", nullable = false)
private String password;
@Column(name="EMAIL", nullable = false, unique = true)
private String email;
@Column(name="ROLE", nullable = false)
private RoleEnum role;
I’m calling this action from a form:
<form role="form" action="#" th:action="@{/user/create}" th:object="${userDTO}" method="post">
and this is my controller:
@RequestMapping(value = "/user/create", method = RequestMethod.POST)
public String handleUserCreateForm(@Valid @ModelAttribute("form") UserDTO form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "user_create";
}
try {
userService.create(form);
} catch (DataIntegrityViolationException e) {
bindingResult.reject("email.exists", "Email already exists");
return "user_create";
}
return "redirect:/users";
}
The validator that cath the error:
private void validateEmail(Errors errors, UserDTO form) {
if (userService.getUserByEmail(form.getEmail()).isPresent()) {
errors.reject("email.exists", "User with this email already exists");
}
}
UserServiceImpl (@Service):
@Override
public Optional<User> getUserByEmail(String email) {
return userRepository.findOneByEmail(email);
}
And the repository is a CrudRepository interface, and have no implementation:
@Repository
public interface UserRepository extends CrudRepository<User, Serializable> {
Optional<User> findOneByEmail(String email);
}
And debuging the validator I could get this stack:
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:238)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:221)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy75.findOneByEmail(Unknown Source)
at com.myapp.service.impl.UserServiceImpl.getUserByEmail(UserServiceImpl.java:32)
at com.myapp.model.validator.UserValidator.validateEmail(UserValidator.java:40)
at com.myapp.model.validator.UserValidator.validate(UserValidator.java:30)
at org.springframework.validation.DataBinder.validate(DataBinder.java:785)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.validateIfApplicable(ModelAttributeMethodProcessor.java:164)
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:111)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:295)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:105)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:68)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2066)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1863)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1839)
at org.hibernate.loader.Loader.doQuery(Loader.java:910)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
at org.hibernate.loader.Loader.doList(Loader.java:2540)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
at org.hibernate.loader.Loader.list(Loader.java:2365)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:497)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:236)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1300)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:573)
at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:495)
at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:71)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:202)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:74)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:99)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:90)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:415)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:393)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java:506)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 98 more
Caused by: org.postgresql.util.PSQLException: ERROR: relation "app_user" does not exist
Posição: 177
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:420)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:305)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 129 more
Thanks for the help!
Solution
PostgreSQL is following the SQL standard and in that case that means that identifiers (table names, column names, etc) are forced to lowercase, except when they are quoted. So when you create a table like this:
CREATE TABLE APP_USER ...
you actually get a table app_user
. You apparently did:
CREATE TABLE "APP_USER" ...
and then you get a table "APP_USER"
.
In Spring, you specify a regular string for the table name, in capital letters, but that gets spliced into a query to the PostgreSQL server without quotes. You can check this by reading the PostgreSQL log files: it should show the query that Spring generated followed by the error at the top of your message.
Since you have very little control over how Spring constructs queries from entities, you are better off using SQL-standard lower-case identifiers.
Answered By — Patrick
Содержание
- Debugging “relation does not exist” error in postgres
- Нельзя просто использовать имя таблицы PostgreSQL («отношение не существует»)
- 7 ответов:
- Нельзя просто использовать имя таблицы PostgreSQL («отношения не существует»)
- org.postgresql.util.PSQLException: ОШИБКА: отношение «app_user» не существует
- 3 ответа
- Java SQL «ОШИБКА: отношение» Имя_таблицы «не существует»
- 4 ответы
Debugging “relation does not exist” error in postgres
So, i was getting this nasty error even when the table clearly existed in t11 database.
Even after lot of googling, debugging and trying Stackoverflow solutions, there was no resolution. Then i got a hunch, that i should check what database and schema were actually being used when done programmatically (even though dbname was clearly provided in connection string).
If you use database t11 by running c t11 and then run:
select * from information_schema.tables where table_schema NOT IN (‘pg_catalog’, ‘information_schema’)
It will tell you that userinfo5 does exist in t11 database. But what happens when we try to access it programmatically?
So, i ran above query in a golang function, the function which was earlier running query select * from userinfo5 where >
Output showed that database name which was actually being used was postgres and not t11 Why?
Because, my postgres user was configured to not use password. But my connection string had password= This was somehow confusing the DB driver and postgres database was being used and not t11 .
remove password= from connection string so that it looks like: “host=localhost port=5432 user=postgres dbname=t11 sslmode=disable”
- Alter user postgres so that it uses password: alter user postgres with password ‘pwd123’;
- Change connection string: “host=localhost port=5432 user=postgres password=pwd123 dbname=t11 sslmode=disable”
Источник
Я пытаюсь запустить следующий PHP-скрипт для выполнения простого запроса к базе данных:
это приводит к следующей ошибке:
ошибка запроса: ошибка: отношение «sf_bands» не существует
во всех примерах я могу найти, где кто-то получает ошибку о том, что связь не существует, это потому, что они используют прописные буквы в имени своей таблицы. Мое имя таблицы не имеет прописных букв. Есть ли способ запросить мою таблицу без включения имени базы данных, т. е. showfinder.sf_bands ?
7 ответов:
из того, что я прочитал, эта ошибка означает, что вы не ссылаетесь на имя таблицы правильно. Одна из распространенных причин заключается в том, что таблица определяется со смешанным написанием, и вы пытаетесь запросить ее со всеми строчными буквами.
другими словами, следующее терпит неудачу:
используйте двойные кавычки для разграничения идентификаторов, чтобы вы могли использовать конкретное смешанное написание, как определено в таблице.
Re ваш комментарий, вы можете добавить схему в «search_path», чтобы при ссылке на имя таблицы без уточнения ее схемы запрос соответствовал этому имени таблицы, проверяя каждую схему по порядку. Так же, как PATH в оболочке или include_path в PHP и др. Вы можете проверить свой текущий путь поиска схема:
вы можете изменить путь поиска схемы:
у меня были проблемы с этим и это история (печальная, но правдивая) :
если ваше имя таблицы все строчные, как: счета вы можете использовать: select * from AcCounTs и он будет работать нормально
если ваше имя таблицы все строчные, как: accounts Следующее не удастся: select * from «AcCounTs»
если ваше имя таблицы смешанный случай как: Accounts Следующее не удастся: select * from accounts
если ваше имя таблицы это смешанный случай как : Accounts Следующее будет работать нормально: select * from «Accounts»
Я не люблю вспоминать бесполезные вещи, как это, но надо 😉
запрос процесса Postgres отличается от других RDMS. Поместите имя схемы в двойную кавычку перед именем таблицы, например, «SCHEMA_NAME».»SF_Bands»
поместите параметр dbname в строку подключения. Это работает для меня, в то время как все остальное не удалось.
также, когда делаешь выбор, указать your_schema . your_table такой:
У меня была аналогичная проблема на OSX, но я пытался играть с двойными и одинарными кавычками. Для вашего случая, вы могли бы попробовать что-то вроде этого
для меня проблема заключалась в том, что я использовал запрос к этой конкретной таблице во время инициализации Django. Конечно, это вызовет ошибку, потому что эти таблицы не существовали. В моем случае это было get_or_create метод в пределах a admin.py файл, который выполнялся всякий раз, когда программное обеспечение выполняло какую-либо операцию (в данном случае миграцию). Надеюсь, это кому-то поможет.
я копал эту проблему больше, и узнал о том, как установить этот «search_path» по defoult для нового пользователя в текущей базе данных.
открыть Свойства базы данных, затем открыть лист » переменные» и просто добавьте эту переменную для вашего пользователя с фактическим значением.
Так что теперь ваш пользователь получит это schema_name по умолчанию, и вы можете использовать tableName без schemaName.
Источник
Нельзя просто использовать имя таблицы PostgreSQL («отношения не существует»)
Я пытаюсь запустить следующий скрипт PHP, чтобы выполнить простой запрос к базе данных:
Это приводит к следующей ошибке:
Ошибка запроса: ERROR: отношения «sf_bands» не существует
Во всех примерах я могу найти, где кто-то получает ошибку, указывающую, что отношения не существует, потому что они используют заглавные буквы в имени своей таблицы. В моем имени таблицы нет заглавных букв. Есть ли способ запросить мою таблицу без включения имени базы данных, то есть showfinder.sf_bands ?
Из того, что я прочитал, эта ошибка означает, что вы неправильно ссылаетесь на имя таблицы. Одной из распространенных причин является то, что таблица определена с орфографией с смешанным регистром, и вы пытаетесь запросить ее со всеми строчными буквами.
Другими словами, следующее не выполняется:
Используйте двойные кавычки, чтобы разграничить идентификаторы, чтобы вы могли использовать конкретную орфографию с смешанным регистром, поскольку таблица определена.
Повторите свой комментарий, вы можете добавить схему в «путь поиска», чтобы при ссылке на имя таблицы без квалификации ее схемы запрос соответствовал этому имени таблицы, проверив каждую схему в порядке. Точно так же, как PATH в оболочке или include_path в PHP и т. Д. Вы можете проверить свой текущий путь поиска схемы:
Вы можете изменить путь поиска схемы:
У меня были проблемы с этим, и это история (грустная, но правда):
Если имя вашей таблицы имеет нижний регистр, например: учетные записи, которые вы можете использовать: select * from AcCounTs и он будет работать нормально
Если ваше имя таблицы имеет все нижеследующее значение, например: accounts Следующие select * from «AcCounTs» не будут выполнены: select * from «AcCounTs»
Если ваше имя таблицы смешанно, например: Accounts : Accounts : select * from accounts
Если ваше имя таблицы смешанно, например: Accounts Следующие будут работать нормально: select * from «Accounts»
Я не люблю вспоминать бесполезные вещи, как это, но вы должны;)
Запрос процесса Postgres отличается от других RDMS. Поместите имя схемы в двойную кавычку перед именем вашей таблицы, например «SCHEMA_NAME». «SF_Bands»
Поместите параметр dbname в строку подключения. Это работает для меня, пока все остальное не удалось.
Также, когда вы делаете выбор, укажите your_schema . your_table :
У меня была аналогичная проблема с OSX, но я старался играть с двойными и одинарными кавычками. В вашем случае вы можете попробовать что-то вроде этого
Источник
org.postgresql.util.PSQLException: ОШИБКА: отношение «app_user» не существует
У меня есть приложение, в котором я использую spring boot и postgres. Я получаю эту ошибку, когда пытаюсь создать пользователя.
Когда я запускаю этот запрос в своей базе данных, я получаю ту же ошибку:
Но если я изменил это на:
Как мне настроить это приложение для загрузки spring?
зависимости в pom.xml:
Я вызываю это действие из формы:
и это мой контроллер:
Валидатор, который исправляет ошибку:
И репозиторий является интерфейсом CrudRepository и не имеет реализации:
И отлаживая валидатор, я мог бы получить этот стек:
Спасибо за помощь!
3 ответа
PostgreSQL соответствует стандарту SQL и в этом случае означает, что идентификаторы (имена таблиц, имена столбцов и т.д.) принудительно строятся в нижнем регистре, за исключением случаев, когда они цитируются. Поэтому, когда вы создаете таблицу следующим образом:
вы фактически получаете таблицу app_user . Вы, очевидно, сделали:
а затем вы получите таблицу «APP_USER» .
В Spring вы указываете правильную строку для имени таблицы заглавными буквами, но ее объединяют в запрос на сервер PostgreSQL без кавычек. Вы можете проверить это, прочитав файлы журнала PostgreSQL: он должен показать запрос, сгенерированный Spring, за которым следует ошибка в верхней части вашего сообщения.
Поскольку у вас очень мало контроля над тем, как Spring строит запросы от сущностей, вам лучше использовать идентификаторы нижнего регистра стандарта SQL.
Источник
Java SQL «ОШИБКА: отношение» Имя_таблицы «не существует»
Я пытаюсь подключить netbeans к моей базе данных postgresql. Кажется, что соединение сработало, поскольку я не получаю никаких ошибок или исключений при простом подключении, такие методы, как getCatalog (), также возвращают правильные ответы.
Но когда я пытаюсь запустить простой оператор SQL, я получаю сообщение об ошибке «ОШИБКА: отношение« TABLE_NAME »не существует», где TABLE_NAME — это любая из моих таблиц, которые ДЕЙСТВИТЕЛЬНО существуют в базе данных. Вот мой код:
Я думал, что netbeans может не находить таблицы, потому что он не ищет схему по умолчанию (общедоступную), есть ли способ установить схему в java?
РЕДАКТИРОВАТЬ: мой код подключения. Имя базы данных — Cinemax, когда я опускаю код оператора, я не получаю ошибок.
Разве нельзя так переписать sql? SELECT * FROM .clients — CoolBeans
Вы не показываете, как вы подключаетесь к серверу базы данных. Я подозреваю, что @CoolBeans верен выше или очень близко. Ваша таблица находится в другой схеме (что будет исправлено выше) или в другой базе данных, чем та, которую вы указали при подключении. — Brian Roach
Мне это нравится . не могли бы вы показать нам НАСТОЯЩУЮ ошибку? Я не думаю, что база данных говорит «отношение TABLE_NAME . », когда вы выполняете «select * from clients». — Szymon Lipiński
Я пробовал это, но получаю ту же ошибку: «ОШИБКА: отношение« public.clients »не существует» (то же самое для любой другой из моих таблиц). public — моя единственная схема, так что это также схема по умолчанию. Спасибо за помощь. — Matt
Установите для log_min_duration_statement значение 0 в postgresql.conf, перезапустите базу данных, запустите приложение и проверьте в журналах postgresql, какой реальный запрос отправляется в базу данных. И еще кое-что . вы на 100% уверены, что у вас есть стол? Можете ли вы подключиться к этой базе данных с помощью psql / pgadmin и выполнить там запрос? — Szymon Lipiński
4 ответы
Я подозреваю, что вы создали таблицу, используя двойные кавычки, например, «Clients» или какая-либо другая комбинация символов верхнего / нижнего регистра, поэтому имя таблицы теперь чувствительно к регистру.
Что означает заявление
Если возвращаемое имя таблицы не в нижнем регистре, вы должны использовать двойные кавычки при обращении к нему, что-то вроде этого:
ответ дан 24 апр.
Я пытаюсь использовать sequelize ORM, и в своем запросе на создание он использует кавычки в table_name. Спасибо за ответ. — Kiddo
Источник
Содержание
- Debugging “relation does not exist” error in postgres
- PostgreSQL relation «mytable» does not exist #1044
- Comments
- sergioszy commented Dec 16, 2017
- Environment
- brettwooldridge commented Dec 16, 2017
- sergioszy commented Dec 16, 2017
- org.postgresql.util.PSQLException:ERROR: relation «contacts» does not exist
- Comments
Debugging “relation does not exist” error in postgres
So, i was getting this nasty error even when the table clearly existed in t11 database.
Even after lot of googling, debugging and trying Stackoverflow solutions, there was no resolution. Then i got a hunch, that i should check what database and schema were actually being used when done programmatically (even though dbname was clearly provided in connection string).
If you use database t11 by running c t11 and then run:
select * from information_schema.tables where table_schema NOT IN (‘pg_catalog’, ‘information_schema’)
It will tell you that userinfo5 does exist in t11 database. But what happens when we try to access it programmatically?
So, i ran above query in a golang function, the function which was earlier running query select * from userinfo5 where >
Output showed that database name which was actually being used was postgres and not t11 Why?
Because, my postgres user was configured to not use password. But my connection string had password= This was somehow confusing the DB driver and postgres database was being used and not t11 .
remove password= from connection string so that it looks like: “host=localhost port=5432 user=postgres dbname=t11 sslmode=disable”
- Alter user postgres so that it uses password: alter user postgres with password ‘pwd123’;
- Change connection string: “host=localhost port=5432 user=postgres password=pwd123 dbname=t11 sslmode=disable”
Источник
PostgreSQL relation «mytable» does not exist #1044
Environment
PreparedStatement prepared = connection.preparedStatement(
«select mytable.column1, mytable.column2 from mytable where mytable.column1 > 0» ); //OK
When execute resultSet = prepared.executeQuery();
throws this exception
org.postgresql.util.PSQLException: ERROR: relation mytable does not exist
Position: 176
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2477)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2190)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:117)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeQuery(ProxyPreparedStatement.java:52)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeQuery(HikariProxyPreparedStatement.java)
The text was updated successfully, but these errors were encountered:
This is not a HikariCP question, this is a PostgreSQL question.
PostgreSQL will not throw an error on prepare, even if the relation does not exist, because the driver will not actually prepare the statement until it has been executed several times. Creating a Statement via Statement stmt = connection.createStatement() , and then executing the same query via resultSet = stmt.executeQuery(«select . «) will fail with the same error.
You may be connecting to PostgreSQL server, but you are not connecting to the database which contains that table. Either specifiy the database, or check that the user has permission to see that table.
But, if I use directly the PGSimpleDatasource everthing is OK. Then the problem is in how HikariCP
Источник
org.postgresql.util.PSQLException:ERROR: relation «contacts» does not exist
Hello, I am pretty new to java and NetBeans. I am getting an error that appears when NetBeans tries to insert a record into a PostgreSQL database. I am using the files that are from a Sun Java tutorial.
————————————-
insert into contacts(id, first_name, last_name)
org.postgresql.util.PSQLException: ERROR: relation «contacts» does not exist
————————————-
I think PostgreSQL needs a SQL statement to formatted like the following: «schema».»tablename»
To include parenthesis around the schema name followed by a dot, followed by the table name. But in the insert statement that NetBeans is creating, just includes the the table name. I have tried to modify the code in different ways, but I can’t get it to format the SQL statement correctly.
I have included the entire statement below. Thanks again for any help.
/**
* Updates the selected contact or inserts a new one (if we are
* in the insert mode).
*
* @param firstName first name of the contact.
* @param lastName last name of the contact.
* @param title title of the contact.
* @param nickname nickname of the contact.
* @param displayFormat display format for the contact.
* @param mailFormat mail format for the contact.
* @param emails email addresses of the contact.
*/
public void updateContact(String firstName, String lastName, String title, String nickname,
int displayFormat, int mailFormat, Object[] emails) <
int selection = getContactSelection().getMinSelectionIndex();
Statement stmt = null;
try <
if (!insertMode) <
rowSet.absolute(selection+1);
>
Connection con = rowSet.getConnection();
stmt = con.createStatement();
String sql;
if (insertMode) <
sql = «insert into public.» + CONTACTS_TABLE + «(» + CONTACTS_KEY + «, » + CONTACTS_FIRST_NAME + «, »
+ CONTACTS_LAST_NAME + «, » + CONTACTS_TITLE + «, » + CONTACTS_NICKNAME + «, »
+ CONTACTS_DISPLAY_FORMAT + «, » + CONTACTS_MAIL_FORMAT + «, » + CONTACTS_EMAIL_ADDRESSES
+ «) values ((case when (select max(» + CONTACTS_KEY + «) from » + CONTACTS_TABLE + «)»
+ «IS NULL then 1 else (select max(» + CONTACTS_KEY + «) from » + CONTACTS_TABLE + «)+1 end), »
+ encodeSQL(firstName) + «, » + encodeSQL(lastName) + «, » + encodeSQL(title) + «, »
+ encodeSQL(nickname) + «, » + displayFormat + «, » + mailFormat + «, »
+ encodeSQL(encodeEmails(emails)) + «)»;
> else <
sql = «update public.» + CONTACTS_TABLE + » set «;
sql += CONTACTS_FIRST_NAME + ‘=’ + encodeSQL(firstName) + «, «;
sql += CONTACTS_LAST_NAME + ‘=’ + encodeSQL(lastName) + «, «;
sql += CONTACTS_TITLE + ‘=’ + encodeSQL(title) + «, «;
sql += CONTACTS_NICKNAME + ‘=’ + encodeSQL(nickname) + «, «;
sql += CONTACTS_DISPLAY_FORMAT + ‘=’ + displayFormat + «, «;
sql += CONTACTS_MAIL_FORMAT + ‘=’ + mailFormat + «, «;
sql += CONTACTS_EMAIL_ADDRESSES + ‘=’ + encodeSQL(encodeEmails(emails));
sql += » where » + CONTACTS_KEY + ‘=’ + rowSet.getObject(CONTACTS_KEY);
>
System.out.println(sql);
stmt.executeUpdate(sql);
rowSet.execute();
> catch (SQLException sqlex) <
sqlex.printStackTrace();
> finally <
setInsertMode(false);
if (stmt != null) <
try <
stmt.close();
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
>
>
>
What’s that «encodeSQL» method doing? You’re much better off with a PreparedStatement, IMO.
No, you don’t need the «public.». Connect to the database and use the table name just as it appears in the Postgres client. That’s what I do. It works fine.
That’s the worst way you can possible build up that SQL statement. Why create all those extra Strings? Better to use a StringBuffer and PreparedStatement.
No transactional logic that I can see. Wouldn’t you want the INSERT to rollback if an exception is caught?
The writeable row set must be a data member of this class. You’ve done nothing to synchronize this method, so it’s not thread safe. Don’t use it with more than one client.
Thanks for your reply.
Knowing that I don’t need the «public» schema keyword helps, but I think I still need the » » double quotes around the table name?
Below is the entire code. Does this look thread safe or like it has any transaction logic?
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
/**
* Model of Contacts application.
*
* @author Jan Stola
*/
public class ContactsModel implements ListSelectionListener <
// Constants for database objects
private static final String CONTACTS_TABLE = «contacts»;
private static final String CONTACTS_KEY = «id»;
private static final String CONTACTS_ID = «id»;
private static final String CONTACTS_FIRST_NAME = «first_name»;
private static final String CONTACTS_LAST_NAME = «last_name»;
private static final String CONTACTS_TITLE = «title»;
private static final String CONTACTS_NICKNAME = «nickname»;
private static final String CONTACTS_DISPLAY_FORMAT = «display_format»;
private static final String CONTACTS_MAIL_FORMAT = «mail_format»;
private static final String CONTACTS_EMAIL_ADDRESSES = «email_addresses»;
// Constants for property names
public static final String PROP_REMOVAL_ENABLED = «removalEnabled»;
public static final String PROP_EDITING_ENABLED = «editingEnabled»;
// RowSet with contacts
private JDBCRowSet rowSet;
// Contacts selection model
private ListSelectionModel contactSelection;
// Insert mode (e.g. are we about to insert a new contact)
private boolean insertMode;
/**
* Getter for rowSet property.
*
* @return rowSet with contacts.
*/
public JDBCRowSet getRowSet() <
return rowSet;
>
/**
* Setter for rowSet property.
*
* @param rowSet rowSet with contacts.
*/
public void setRowSet(JDBCRowSet rowSet) <
this.rowSet = rowSet;
>
/**
* Getter for contactSelection property.
*
* @return contacts selection model.
*/
public ListSelectionModel getContactSelection() <
if (contactSelection == null) <
contactSelection = new DefaultListSelectionModel();
contactSelection.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setContactSelection(contactSelection);
>
return contactSelection;
>
/**
* Setter for contactSelection property.
*
* @param contactSelection contacts selection model.
*/
public void setContactSelection(ListSelectionModel contactSelection) <
if (this.contactSelection != null) <
this.contactSelection.removeListSelectionListener(this);
>
this.contactSelection = contactSelection;
contactSelection.addListSelectionListener(this);
>
/**
* Setter for insertMode property.
*
* @param insertMode insert mode.
*/
void setInsertMode(boolean insertMode) <
this.insertMode = insertMode;
>
/**
* Returns ID of the selected contact.
*
* @return ID of the selected contact.
*/
public String getID() <
return insertMode ? null : stringValue(CONTACTS_ID);
>
/**
* Returns the first name of the selected contact.
*
* @return the first name of the selected contact.
*/
public String getFirstName() <
return insertMode ? «» : stringValue(CONTACTS_FIRST_NAME);
>
/**
* Returns the last name of the selected contact.
*
* @return the last name of the selected contact.
*/
public String getLastName() <
return insertMode ? «» : stringValue(CONTACTS_LAST_NAME);
>
/**
* Returns title of the selected contact.
*
* @return title of the selected contact.
*/
public String getTitle() <
return insertMode ? «» : stringValue(CONTACTS_TITLE);
>
/**
* Returns nickname of the selected contact.
*
* @return nickname of the selected contact.
*/
public String getNickname() <
return insertMode ? «» : stringValue(CONTACTS_NICKNAME);
>
/**
* Returns display format of the selected contact.
*
* @return display format of the selected contact.
*/
public int getDisplayFormat() <
return insertMode ? 0 : intValue(CONTACTS_DISPLAY_FORMAT);
>
/**
* Returns mail format of the selected contact.
*
* @return mail format of the selected contact.
*/
public int getMailFormat() <
return insertMode ? 0 : intValue(CONTACTS_MAIL_FORMAT);
>
/**
* Returns email addresses of the selected contact.
*
* @return email addresses of the selected contact.
*/
public Object[] getEmails() <
String encodedEmails = insertMode ? null : stringValue(CONTACTS_EMAIL_ADDRESSES);
return decodeEmails(encodedEmails);
>
/**
* Determines whether editing of the selected contact is enabled.
*
* @return true if the selected contact can be edited,
* returns false otherwise.
*/
public boolean isEditingEnabled() <
// Additional business logic can go here
return (getContactSelection().getMinSelectionIndex() != -1);
>
/**
* Determines whether removal of the selected contact is enabled.
*
* @return true if the selected contact can be removed,
* returns false otherwise.
*/
public boolean isRemovalEnabled() <
// Additional business logic can go here
return (getContactSelection().getMinSelectionIndex() != -1);
>
// Helper method that returns value of a selected contact’s attribute
private String stringValue(String columnName) <
String value = null;
try <
if ((rowSet != null) && selectContactInRowSet()) <
value = rowSet.getString(columnName);
>
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
return value;
>
// Helper method that returns value of a selected contact’s attribute
private int intValue(String columnName) <
int value = 0;
try <
if ((rowSet != null) && selectContactInRowSet()) <
value = rowSet.getInt(columnName);
>
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
return value;
>
// Helper method that synchronizes rowSet position with selected contact
private boolean selectContactInRowSet() <
int index = getContactSelection().getMinSelectionIndex();
if (index != -1) <
try <
rowSet.absolute(index+1);
> catch (SQLException sqlex) <
sqlex.printStackTrace();
>
>
return (index != -1);
>
// Helper method that decodes email addresses from the encoded string
private Object[] decodeEmails(String encodedEmails) <
if ((encodedEmails == null) || (encodedEmails.equals(«»))) <
return new String[0];
>
char sep = encodedEmails.charAt(0);
List emails = new LinkedList();
StringTokenizer st = new StringTokenizer(encodedEmails, String.valueOf(sep));
while (st.hasMoreTokens()) <
emails.add(st.nextToken());
>
return emails.toArray(new Object[emails.size()]);
>
// Helper method that encodes email addresses into one string
private String encodeEmails(Object[] emails) <
StringBuffer sb = new StringBuffer();
for (int i=0; i 0 · Share on Twitter Share on Facebook
Источник