0

I am trying to insert a value(http://localhost:8080/create?name=name1&email=name1@email.com) to Postgres DB using SpringBoot and hibernate but in log it says as it inserts but no records are inserted also no exception is there.Please help me to find the issue.

Postgres Version:

"PostgreSQL 9.6.3 on x86_64-pc-mingw64, compiled by gcc.exe (Rev5, Built by MSYS2 project) 4.9.2, 64-bit"

build.gradle:

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'eclipse'

group = 'netgloo'
version = '0.0.1-SNAPSHOT'

description = """spring-boot-mysql-springdatajpa-hibernate"""

sourceCompatibility = 1.8
targetCompatibility = 1.8
tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}    
repositories {

     maven { url "http://repo.maven.apache.org/maven2" }
}
dependencies {
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version:'1.5.2.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version:'1.5.2.RELEASE'
    compile group: 'postgres', name: 'postgres', version:'42.1.1.jre6'
}

User.java:

@Entity
@Table(name = "users")
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;
  @NotNull
  private String email;
  @NotNull
  private String name;

  public User() { }

  public User(long id) { 
    this.id = id;
  }

  public User(String email, String name) {
    this.email = email;
    this.name = name;
  }


  public long getId() {
    return id;
  }

  public void setId(long value) {
    this.id = value;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String value) {
    this.email = value;
  }

  public String getName() {
    return name;
  }

  public void setName(String value) {
    this.name = value;
  }  
} 

Controller:

@Controller
public class UserController {

  @RequestMapping("/create")
  @ResponseBody
  public String create(String email, String name) {
    User user = null;
    try {
      user = new User(email, name);
      userDao.save(user);
    }
    catch (Exception ex) {
      return "Error creating the user: " + ex.toString();
    }
    return "User succesfully created! (id = " + user.getId() + ")";
  }

  @RequestMapping("/get-by-email")
  @ResponseBody
  public String getByEmail(String email) {
    String userId;
    try {
      User user = userDao.findByEmail(email);
      userId = String.valueOf(user.getId());
    }
    catch (Exception ex) {
      return "User not found";
    }
    return "The user id is: " + userId;
  }
}

UserDao:

@Transactional
public interface UserDao extends CrudRepository<User, Long> {

  public User findByEmail(String email);

} // class UserDao

logs:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
[32m :: Spring Boot :: [39m      [2m (v1.5.2.RELEASE)[0;39m

[2m2017-07-07 14:54:59.528[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mnetgloo.Application                     [0;39m [2m:[0;39m Starting Application on B20GPF2 with PID 17176 (C:\Users\a591470\projects\mylearning\spring-boot-samples-master\spring-boot-mysql-springdatajpa-hibernate\bin started by a591470 in C:\Users\a591470\projects\mylearning\spring-boot-samples-master\spring-boot-mysql-springdatajpa-hibernate)
[2m2017-07-07 14:54:59.533[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mnetgloo.Application                     [0;39m [2m:[0;39m No active profile set, falling back to default profiles: default
[2m2017-07-07 14:54:59.652[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mationConfigEmbeddedWebApplicationContext[0;39m [2m:[0;39m Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4387b79e: startup date [Fri Jul 07 14:54:59 IST 2017]; root of context hierarchy
[2m2017-07-07 14:55:01.391[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mtrationDelegate$BeanPostProcessorChecker[0;39m [2m:[0;39m Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$61eecdd6] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[2m2017-07-07 14:55:01.919[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.b.c.e.t.TomcatEmbeddedServletContainer[0;39m [2m:[0;39m Tomcat initialized with port(s): 8080 (http)
[2m2017-07-07 14:55:01.935[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.apache.catalina.core.StandardService  [0;39m [2m:[0;39m Starting service Tomcat
[2m2017-07-07 14:55:01.936[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.apache.catalina.core.StandardEngine [0;39m [2m:[0;39m Starting Servlet Engine: Apache Tomcat/8.5.11
[2m2017-07-07 14:55:02.170[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[ost-startStop-1][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/]      [0;39m [2m:[0;39m Initializing Spring embedded WebApplicationContext
[2m2017-07-07 14:55:02.171[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[ost-startStop-1][0;39m [36mo.s.web.context.ContextLoader           [0;39m [2m:[0;39m Root WebApplicationContext: initialization completed in 2525 ms
[2m2017-07-07 14:55:02.466[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[ost-startStop-1][0;39m [36mo.s.b.w.servlet.ServletRegistrationBean [0;39m [2m:[0;39m Mapping servlet: 'dispatcherServlet' to [/]
[2m2017-07-07 14:55:02.472[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[ost-startStop-1][0;39m [36mo.s.b.w.servlet.FilterRegistrationBean  [0;39m [2m:[0;39m Mapping filter: 'characterEncodingFilter' to: [/*]
[2m2017-07-07 14:55:02.472[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[ost-startStop-1][0;39m [36mo.s.b.w.servlet.FilterRegistrationBean  [0;39m [2m:[0;39m Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
[2m2017-07-07 14:55:02.472[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[ost-startStop-1][0;39m [36mo.s.b.w.servlet.FilterRegistrationBean  [0;39m [2m:[0;39m Mapping filter: 'httpPutFormContentFilter' to: [/*]
[2m2017-07-07 14:55:02.472[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[ost-startStop-1][0;39m [36mo.s.b.w.servlet.FilterRegistrationBean  [0;39m [2m:[0;39m Mapping filter: 'requestContextFilter' to: [/*]
[2m2017-07-07 14:55:04.067[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mj.LocalContainerEntityManagerFactoryBean[0;39m [2m:[0;39m Building JPA container EntityManagerFactory for persistence unit 'default'
[2m2017-07-07 14:55:04.103[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.hibernate.jpa.internal.util.LogHelper [0;39m [2m:[0;39m HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
[2m2017-07-07 14:55:04.304[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.hibernate.Version                   [0;39m [2m:[0;39m HHH000412: Hibernate Core {5.0.12.Final}
[2m2017-07-07 14:55:04.306[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.hibernate.cfg.Environment           [0;39m [2m:[0;39m HHH000206: hibernate.properties not found
[2m2017-07-07 14:55:04.309[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.hibernate.cfg.Environment           [0;39m [2m:[0;39m HHH000021: Bytecode provider name : javassist
[2m2017-07-07 14:55:04.388[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.hibernate.annotations.common.Version  [0;39m [2m:[0;39m HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
[2m2017-07-07 14:55:04.602[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.hibernate.dialect.Dialect           [0;39m [2m:[0;39m HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
[2m2017-07-07 14:55:04.920[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.h.e.j.e.i.LobCreatorBuilderImpl       [0;39m [2m:[0;39m HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
[2m2017-07-07 14:55:04.923[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.hibernate.type.BasicTypeRegistry    [0;39m [2m:[0;39m HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@2f84acf7
[2m2017-07-07 14:55:05.243[0;39m [33m WARN[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.hibernate.orm.deprecation           [0;39m [2m:[0;39m HHH90000014: Found use of deprecated [org.hibernate.id.SequenceGenerator] sequence-based id generator; use org.hibernate.id.enhanced.SequenceStyleGenerator instead.  See Hibernate Domain Model Mapping Guide for details.
[2m2017-07-07 14:55:05.724[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36morg.hibernate.tool.hbm2ddl.SchemaUpdate [0;39m [2m:[0;39m HHH000228: Running hbm2ddl schema update
[2m2017-07-07 14:55:05.877[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mj.LocalContainerEntityManagerFactoryBean[0;39m [2m:[0;39m Initialized JPA EntityManagerFactory for persistence unit 'default'
[2m2017-07-07 14:55:06.920[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerAdapter[0;39m [2m:[0;39m Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4387b79e: startup date [Fri Jul 07 14:54:59 IST 2017]; root of context hierarchy
[2m2017-07-07 14:55:07.038[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Mapped "{[/]}" onto public java.lang.String netgloo.controllers.MainController.index()
[2m2017-07-07 14:55:07.040[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Mapped "{[/delete]}" onto public java.lang.String netgloo.controllers.UserController.delete(long)
[2m2017-07-07 14:55:07.040[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Mapped "{[/create]}" onto public java.lang.String netgloo.controllers.UserController.create(java.lang.String,java.lang.String) throws java.lang.Exception
[2m2017-07-07 14:55:07.041[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Mapped "{[/update]}" onto public java.lang.String netgloo.controllers.UserController.updateUser(long,java.lang.String,java.lang.String)
[2m2017-07-07 14:55:07.041[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Mapped "{[/get-by-email]}" onto public java.lang.String netgloo.controllers.UserController.getByEmail(java.lang.String) throws java.lang.Exception
[2m2017-07-07 14:55:07.044[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
[2m2017-07-07 14:55:07.045[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.w.s.m.m.a.RequestMappingHandlerMapping[0;39m [2m:[0;39m Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
[2m2017-07-07 14:55:07.113[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.w.s.handler.SimpleUrlHandlerMapping [0;39m [2m:[0;39m Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[2m2017-07-07 14:55:07.113[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.w.s.handler.SimpleUrlHandlerMapping [0;39m [2m:[0;39m Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[2m2017-07-07 14:55:07.172[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.w.s.handler.SimpleUrlHandlerMapping [0;39m [2m:[0;39m Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
[2m2017-07-07 14:55:07.557[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mo.s.j.e.a.AnnotationMBeanExporter       [0;39m [2m:[0;39m Registering beans for JMX exposure on startup
[2m2017-07-07 14:55:08.132[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36ms.b.c.e.t.TomcatEmbeddedServletContainer[0;39m [2m:[0;39m Tomcat started on port(s): 8080 (http)
[2m2017-07-07 14:55:08.138[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[           main][0;39m [36mnetgloo.Application                     [0;39m [2m:[0;39m Started Application in 9.279 seconds (JVM running for 11.078)
[2m2017-07-07 14:55:22.454[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/]      [0;39m [2m:[0;39m Initializing Spring FrameworkServlet 'dispatcherServlet'
[2m2017-07-07 14:55:22.454[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet       [0;39m [2m:[0;39m FrameworkServlet 'dispatcherServlet': initialization started
[2m2017-07-07 14:55:22.692[0;39m [32m INFO[0;39m [35m17176[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36mo.s.web.servlet.DispatcherServlet       [0;39m [2m:[0;39m FrameworkServlet 'dispatcherServlet': initialization completed in 237 ms
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into users (email, name, id) values (?, ?, ?)
sunleo
  • 10,589
  • 35
  • 116
  • 196
  • Can you also add your User class? Possibly the user gets no id? – Fortega Jul 07 '17 at 09:38
  • @Fortega thanks for your reply, please check I included the User.java. – sunleo Jul 07 '17 at 09:42
  • How is your id key declared in the database ? – Arnaud Jul 07 '17 at 09:48
  • 2
    Check your application.properties file if it correct try the following, add @Repository to your UserDao, and add @EnableJpaRepositories(basePackages = {"Your dao path"}) to main class – Almas Abdrazak Jul 07 '17 at 09:49
  • @Berger , CREATE TABLE orders.users ( id bigserial NOT NULL, name text NOT NULL, email text NOT NULL, CONSTRAINT users_pkey PRIMARY KEY (id) ); – sunleo Jul 07 '17 at 09:57
  • @AlmasAbdrazak adding `@EnableJpaRepositories` will disable auto-configuration, adding `@Repository` to a Spring Data repository interface is useless. – M. Deinum Jun 15 '22 at 13:23
  • @sunleo what makes you think that the data isn't inserted? Did you look in the database or did you try with a database explorer? – M. Deinum Jun 15 '22 at 13:23

2 Answers2

1

When you use a serial or a bigserial field in a Postgre table, it is an auto-increment field for which a sequence is automatically created.

This can cause trouble with the sequence used by hibernate by default (hibernate_sequence) when using GenerationType.AUTO.

To avoid that, you may either rely on the id generator of your serial field :

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY)

Or you may find the sequence (1) that the bigserial has generated (let's call it user_id_seq for this example), and specify it in your annotations so that hibernate uses this one directly :

@Id 
@SequenceGenerator(name = "seqUser", sequenceName = "user_id_seq", allocationSize = 1)
@GeneratedValue(generator = "seqUser", strategy = GenerationType.AUTO)

(1): in the table script, you probably have something like the following, telling you the name of the sequence used by Postgre for the increment (usually it is like : table name_column name_seq).

id bigint NOT NULL DEFAULT nextval('user_id_seq'::regclass)

Some more information about serial fields can be found in this question : PostgreSQL bigserial & nextval

Ans some information about GenerationType strategies with Postgre : JPA and PostgreSQL with GenerationType.IDENTITY

Arnaud
  • 17,229
  • 3
  • 31
  • 44
1

create a service class and add your method to call Dao(Repo ) and make sure that the method is transactional
then from controller call the service instead of calling the dao

Amro Nahas
  • 44
  • 4