Using MySQL in Spring Boot via Spring Data JPA and Hibernate

This post shows how to use a MySQL database in a Spring Boot web application, using less code and configurations as possible, with the aim to take full advantage from Spring Boot.
Spring Data JPA and Hibernate (as JPA implementation) will be used to implement the data access layer.

Dependencies

Be sure to have following dependencies in the pom.xml file:

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
  </dependency>
</dependencies>

See here an example of a whole pom.xml.

Configuration file

Put in the application.properties file pretty much all the configurations:

src/main/resources/application.properties
# DataSource settings: set here your own configurations for the database 
# connection. In this example we have "netgloo_blog" as database name and 
# "root" as username and password.
spring.datasource.url = jdbc:mysql://localhost:8889/netgloo_blog
spring.datasource.username = root
spring.datasource.password = root

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update

# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

No xml or java config classes are needed.

Using the hibernate configuration ddl-auto = update the database schema will be automatically created (and updated), creating tables and columns, accordingly to java entities found in the project.

See here for other hibernate specific configurations.

Create an entity

Create an entity class representing a table in your db.

In this example we create an entity User composed by three fields: id, email and name.
An object of this class will be an entry in the users table in your MySQL database.

src/main/java/netgloo/models/User.java
package netgloo.models;

// Imports ...

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

  // An autogenerated id (unique for each user in the db)
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;
  
  @NotNull
  private String email;
  
  @NotNull
  private String name;

  // Public methods
  
  public User() { }

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

  // Getter and setter methods
  // ...

}

The Entity annotation mark this class as a JPA entity. The Table annotation specifies the db table’s name (would be “User” as default).

The Data Access Object

A DAO (aka Repository) is needed to works with entities in database’s table, with methods like save, delete, update, etc.

With Spring Data JPA a DAO for your entity is simply created by extending the CrudRepository interface provided by Spring. The following methods are some of the ones available from such interface: save, delete, deleteAll, findOne and findAll.
The magic is that such methods must not be implemented, and moreover it is possible to create new query methods working only by their signature definition!

Here there is the Dao class UserDao for our entity User:

src/main/java/netgloo/models/UserDao.java
package netgloo.models;

// Imports ...

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

  /**
   * This method will find an User instance in the database by its email.
   * Note that this method is not implemented and its working code will be
   * automagically generated from its signature by Spring Data JPA.
   */
  public User findByEmail(String email);

}

See here for more details on how to create query from method names.

A controller for testing

That’s all! The connection with the database is done. Now we can test it.

In the same way as in some similar previous post (one and two) we create a controller class named UserController to test interactions with the MySQL database using the UserDao class.

src/main/java/netgloo/controllers/UserController.java
package netgloo.controllers;

// Imports ...

@Controller
public class UserController {

  /**
   * GET /create  --> Create a new user and save it in the database.
   */
  @RequestMapping("/create")
  @ResponseBody
  public String create(String email, String name) {
    String userId = "";
    try {
      User user = new User(email, name);
      userDao.save(user);
      userId = String.valueOf(user.getId());
    }
    catch (Exception ex) {
      return "Error creating the user: " + ex.toString();
    }
    return "User succesfully created with id = " + userId;
  }
  
  /**
   * GET /delete  --> Delete the user having the passed id.
   */
  @RequestMapping("/delete")
  @ResponseBody
  public String delete(long id) {
    try {
      User user = new User(id);
      userDao.delete(user);
    }
    catch (Exception ex) {
      return "Error deleting the user:" + ex.toString();
    }
    return "User succesfully deleted!";
  }
  
  /**
   * GET /get-by-email  --> Return the id for the user having the passed
   * email.
   */
  @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;
  }
  
  /**
   * GET /update  --> Update the email and the name for the user in the 
   * database having the passed id.
   */
  @RequestMapping("/update")
  @ResponseBody
  public String updateUser(long id, String email, String name) {
    try {
      User user = userDao.findOne(id);
      user.setEmail(email);
      user.setName(name);
      userDao.save(user);
    }
    catch (Exception ex) {
      return "Error updating the user: " + ex.toString();
    }
    return "User succesfully updated!";
  }

  // Private fields

  @Autowired
  private UserDao userDao;
  
}

Test the controller launching the Spring Boot web application and using these urls:

  • /create?email=[email]&name=[name]: create a new user with an auto-generated id and email and name as passed values.
  • /delete?id=[id]: delete the user with the passed id.
  • /get-by-email?email=[email]: retrieve the id for the user with the given email address.
  • /update?id=[id]&email=[email]&name=[name]: update the email and the name for the user identified by the given id.

Get the whole code

You can get the whole code used in this post from our Github repository here:

https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-mysql-springdatajpa-hibernate

References

  • Render

    Not working. `Cannot autowire bean` in UserController

    • Hi, have you tried with the code from our github repo? It’s linked at the end of the post, in the “Get the whole code” section. It should works. Maybe there is something missing in your project. Let me know.

    • Dogbert

      Just add @EnableJpaRepositories to Application class.

    • bamueller

      I am getting the same error. The UserDao is an interface. AFAIK, there is not implementation of it, which is the bean. What settings am I missing? Thanks!

  • Robertas Šetkus

    yep, cannot autowire dao object in controller and yes i have tried code in github repo.

    • Please try the following: download the code from github, put in the application.properties your own configurations, make sure you have java 7 or 8 and maven 3, from the root of the project folder type these commands:

      $ mvn package
      $ java -jar target/spring-boot-mysql-springdatajpa-hibernate-0.0.1-SNAPSHOT.jar

      It must works. Let me know if you make a try.

  • Kevin

    It works like a charm. Thanks andrea

  • ssd

    This is amazing!! Thank you so much for all the help!!!! One of the best boot strap tutorials I have seen!

  • Evan Hu

    Great thanks for your work. I am doing the same thing right now. Spring Boot is cool. Just with a few lines of code, a complete REST end point can be up and running!

    By the way, I think we can write less code, for example omit the configuration “spring.jpa.database = MYSQL” & “spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect”. I didn’t write them and my sample project is running well. ^_^

    • Yes, thanks for your suggestion.. I will update the post.

  • Fabian Calsina

    Thank you very much!. It was helpful for me

  • Senthil Muthiah

    Hi
    Excellent Article. But i just wonder where you are specifiying the hiberate version ?

    • Hi! Hibernate comes with spring-boot-starter-data-jpa so you get the version specified there. But I think you can override such version in some way if you want to specify your own.

  • Shanmugapriya M

    Hi I did some changes in this code … in DAO class i changed to

    public Tenant findByTenant_Name(String name);
    instead of email…

    in controller class i did this
    @RequestMapping(“/get-by-tenant_name”)
    @ResponseBody
    public String getByTenantName(String name) {
    String userId;
    try {
    Tenant tenant = userDao.findByTenant_Name(name);
    userId = String.valueOf(tenant.getTenant_id());
    }
    catch (Exception ex) {
    return “User not found”;
    }
    return “The user id is: ” + userId;
    }

    im getting this error… can you plz guide me solve this..??

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userController’: Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private netgloo.models.UserDao netgloo.controllers.UserController.userDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userDao’: Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property tenant found for type Tenant!
    TIA

    • Do you implemented all getters/setters methods on your Tenant class?.. It could be also a problem due to some wrong name, take a look here for naming conventions using Spring Data Jpa.

      But it’s better to use StackOverflow for these type of problems. Then you could post here the link to your question (and I will be happy to help you 🙂 )

      • Shanmugapriya M

        Thanks for your reply… Finally I got a solution… I gave the variable name as tenant_name… If I give as tenantName its working… Underscore was removed tats all I did.

        • Good!

          • Shanmugapriya M

            But wats the prob with underscore… Why it didn’t work..? Any idea?

          • Spring Data JPA use some conventions, especially creating queries from method names. It is explained in the link I give you above (here). I think the use of underscore in field names should be avoided. Take a look also here.

  • John London

    When I try to put the code that’s currently in the REST controller that creates an entity into the run() method on the main Spring application class, it doesn’t work (an entity isn’t created). Do you know why this might happen please?

    • Maybe your code is executed before Spring instantiate the beans. Do you get some error?
      You can try with this if you want to run some code at Spring Boot’s startup.

  • Sumanth N

    Thanks for sharing example;very helpful

  • Sean R

    This tutorials snippets really helped me connect the dots on Hibernate/JPA and Spring. Thank you so much for presenting this so simply AND for citing your direct sources, just awesome!

  • lrnt K

    Thank you very much, very helpful. To do after this : http://spring.io/guides/gs/accessing-data-jpa/

  • Faisal Arkan

    thank so much,, it’s really helpful !

  • Yesid Yesid

    Nice!, really helpful to me 🙂

  • Antonio Cesar

    Perfect!!!

  • commonpeople

    I was trying to run this code from eclipse , and got this error
    Failed to instantiate [javax.sql.DataSource]: Factory method ‘dataSource’ threw exception;
    Spent a few days trying to get it to work.
    At the end, i read git hub again , the writter clearly says run from console or run as springBoot app !
    did this : mvn spring-boot:run
    And app works like a charm
    Thanks

    • WHK Yan

      Same problem

  • Emiliano Riva

    Hey thanks for the great post, i’m experiencing problems running the application in an external tomcat7, catalina give me this error “NoSuchMethodError: java.util.concurrent.ConcurrentHashMap.keySet()Ljava/util/concurrent/ConcurrentHashMap$KeySetView;” this is what say the doc: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-create-a-deployable-war-file,
    i’m building war with maven3 🙂 and there is jdk7 in the environment, can you check please?
    Stack question (http://stackoverflow.com/questions/37054719/the-requested-resource-is-not-available-deploy-spring-boot-application-in-tomc?noredirect=1#comment61693558_37054719)

  • Bastien

    Thank you a lot, I’ve learn so much with your example. Thanks to the other person who comment this tuto, you help me too.
    But I still have an error when I want to create an new USER :
    Error creating the user: org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement
    Does somebody knows why ?

    • Hello Bastien, are you running the code above in this post or did you done some customizations? You can try to download the whole code from our github repository and running it. It should works. Then try to change it to get what you want and understand what is causing the error you have now.

      • Bastien

        Hello, yes, the code was good, I check it so many times haha…
        but I’ve made a mistake in the description of my data base. That’s why an Hibernate exception was appeared. Problem solved, Thanks 😉

  • MB

    I made no changes, but get
    MySQLSyntaxErrorException: Unknown database ‘netgloo_blog’

    • Looks like you didn’t created the database in MySQL. You can create one named netgloo_blog or one with the name you want and configure the database name within the application.properties. Also do not forget to set username and password correctly.

  • MB

    Thanks, in reply to your email I created the DB and everything works. Nice.

  • Chetan Khatri

    I am getting below Error:
    “org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile”

    Entire print error stack

    2016-08-17 11:03:14.714 ERROR 5786 — [ main] o.s.boot.SpringApplication : Application startup failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at netgloo.Application.main(Application.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
    at java.lang.Thread.run(Thread.java:745)
    Caused by: java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile
    at org.hibernate.jpa.boot.scan.spi.ClassFileArchiveEntryHandler.toClassFile(ClassFileArchiveEntryHandler.java:85)
    at org.hibernate.jpa.boot.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:65)
    at org.hibernate.jpa.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:176)
    at org.hibernate.jpa.boot.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:72)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.scan(EntityManagerFactoryBuilderImpl.java:725)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.(EntityManagerFactoryBuilderImpl.java:221)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.(EntityManagerFactoryBuilderImpl.java:188)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider$1.(SpringHibernateJpaPersistenceProvider.java:49)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:49)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    … 21 common frames omitted
    Caused by: java.lang.ClassNotFoundException: javassist.bytecode.ClassFile
    at java.net.URLClassLoader$1.run(URLClassLoader.java:370)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at org.springframework.boot.loader.LaunchedURLClassLoader.doLoadClass(LaunchedURLClassLoader.java:170)
    at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:136)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    … 34 common frames omitted
    Caused by: java.util.zip.ZipException: invalid distance too far back
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
    at org.springframework.boot.loader.jar.ZipInflaterInputStream.read(ZipInflaterInputStream.java:52)
    at sun.misc.Resource.getBytes(Resource.java:124)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:462)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    … 41 common frames omitted

    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:53)
    at java.lang.Thread.run(Thread.java:745)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘entityManagerFactory’ defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:957)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:946)
    at netgloo.Application.main(Application.java:10)
    … 6 more
    Caused by: java.lang.NoClassDefFoundError: javassist/bytecode/ClassFile
    at org.hibernate.jpa.boot.scan.spi.ClassFileArchiveEntryHandler.toClassFile(ClassFileArchiveEntryHandler.java:85)
    at org.hibernate.jpa.boot.scan.spi.ClassFileArchiveEntryHandler.handleEntry(ClassFileArchiveEntryHandler.java:65)
    at org.hibernate.jpa.boot.archive.internal.JarFileBasedArchiveDescriptor.visitArchive(JarFileBasedArchiveDescriptor.java:176)
    at org.hibernate.jpa.boot.scan.spi.AbstractScannerImpl.scan(AbstractScannerImpl.java:72)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.scan(EntityManagerFactoryBuilderImpl.java:725)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.(EntityManagerFactoryBuilderImpl.java:221)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.(EntityManagerFactoryBuilderImpl.java:188)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider$1.(SpringHibernateJpaPersistenceProvider.java:49)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:49)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
    … 21 more
    Caused by: java.lang.ClassNotFoundException: javassist.bytecode.ClassFile
    at java.net.URLClassLoader$1.run(URLClassLoader.java:370)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at org.springframework.boot.loader.LaunchedURLClassLoader.doLoadClass(LaunchedURLClassLoader.java:170)
    at org.springframework.boot.loader.LaunchedURLClassLoader.loadClass(LaunchedURLClassLoader.java:136)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    … 34 more
    Caused by: java.util.zip.ZipException: invalid distance too far back
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
    at org.springframework.boot.loader.jar.ZipInflaterInputStream.read(ZipInflaterInputStream.java:52)
    at sun.misc.Resource.getBytes(Resource.java:124)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:462)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)

    • Hello Chetan, are you running the code above in this post or did you done some customizations?
      You can try to download the whole code from our github repository and running it. It should works. Then try to change it to get what you want and understand what is causing the error you have now.
      Hope this wil help you.

  • joho_w

    Hi, the github link didn’t work in my Eclipse Neon. Could you have a check?

  • Michael

    how do i list all the users in a html table?

    • Hi Michael, sorry but this post is about How to use MySQL with Spring Boot. Showing a list of users is not the aim of this post. You should try to use the method findAll from the UserDao class to get the list of all users. Than you can iterate over such list and generate the HTML.
      If you are using Thymeleaf, you can use th:each: http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-theach

  • Petr Knapek

    Hi,
    thanks a lot for the tutorial, it is great for me as a spring begginer.
    Although I have a problem running this tutorials code. Ir runs fine in IDE but created .jar artifact doesnt work at all. Any suggestions, please?

    • Did you tried one of these?:

      Gradle:


      ./gradlew build && java -jar build/libs/gs-spring-boot-0.1.0.jar

      Maven:


      mvn package && java -jar target/gs-spring-boot-0.1.0.jar

      Take a look here for more: https://spring.io/guides/gs/spring-boot/

      • Petr Knapek

        I can build it and create .jar just fine. It just doesn’t run properly and throws errors that IDE doesn’t. Always shows missing configuration and beans.

  • akshay gupta

    I am getting below error while running with inbuilt springboot tomcat. pls help

    Field userDao in netgloo.controller.UserController required a bean of type ‘netgloo.model.UserDao’ that could not be found.

    • Please post a question on stackoverflow, with as much details as possible (all your relevant code, commands you are using to compile and launch your application, the full error you are getting). Then leave a link to your question here.
      I will be happy to help you if I can.
      Thank you.

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2016 Netgloo