Using MySQL in Spring Boot Via Spring Data JPA
Using MySQL in Spring Boot Via Spring Data JPA
USING MYSQL IN SPRING BOOT VIA SPRING DATA JPA AND HIBERNATE
SPRING ANDREA 27 October 2014 62 COMMENTS
This post shows how to use a MySQL database in a Spring Boot web application, using less code and con gurations 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 le:
1 <dependencies
dependencies>>
2 <dependency
dependency>>
3 <groupId
groupId>
>org.springframework.boot
org.springframework.boot</
</groupId
groupId>
>
4 <artifactId
artifactId> >spring-boot-starter-web
spring-boot-starter-web</
</artifactId
artifactId>
>
5 </dependency>
</dependency >
6 <dependency
dependency>>
7 <groupId
groupId>
>org.springframework.boot
org.springframework.boot</</groupId
groupId>
>
8 <artifactId
artifactId> >spring-boot-starter-data-jpa
spring-boot-starter-data-jpa</
</artifactId
artifactId>
>
9 </dependency
</dependency> >
10 <dependency
dependency>>
11 <groupId
groupId>
>mysql
mysql</</groupId
groupId>
>
12 <artifactId
artifactId> >mysql-connector-java
mysql-connector-java</
</artifactId
artifactId>
>
13 </dependency
</dependency> >
14 </dependencies
</dependencies> >
Configuration file
Put in the application.properties le pretty much all the con gurations:
src/main/resources/application.properties
1 # DataSource settings: set here your own configurations for the database
2 # connection. In this example we have "netgloo_blog" as database name and
3 # "root" as username and password.
4 spring.datasource.url = jdbc:mysql://localhost:8889/netgloo_blog
5 spring.datasource.username = root
6 spring.datasource.password = root
7
8 # Keep the connection alive if idle for a long time (needed in production)
9 spring.datasource.testWhileIdle = true
10 spring.datasource.validationQuery = SELECT 1
11
12 # Show or not log for each sql query
13 spring.jpa.show-sql = true
14
15 # Hibernate ddl auto (create, create-drop, update)
16 spring.jpa.hibernate.ddl-auto = update
17
18 # Naming strategy
19 spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
20
21 # Use spring.jpa.properties.* for Hibernate native properties (the prefix is
22 # stripped before adding them to the entity manager)
23
24 # The SQL dialect makes Hibernate generate better SQL for the chosen database
25 spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 1/9
7/5/2019 Using MySQL in Spring Boot via Spring Data JPA and Hibernate – Netgloo Blog
No xml or java con g classes are needed.
Using the hibernate con guration ddl-auto = update the database schema will be automatically created (and updated), creating tables and columns, accordingly to java entities
found in the project.
Create an entity
Create an entity class representing a table in your db.
In this example we create an entity User composed by three elds: 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
1 package netgloo
netgloo..models
models;
;
2
3 // Imports ...
4
5 @Entity
6 @Table(
@Table(name = "users"
"users")
)
7 public class User {
8
9 // An autogenerated id (unique for each user in the db)
10 @Id
11 @GeneratedValue(
@GeneratedValue (strategy = GenerationType
GenerationType.
.AUTO
AUTO)
)
12 private long id
id;
;
13
14 @NotNull
15 private String email;
email;
16
17 @NotNull
18 private String name;
name;
19
20 // Public methods
21
22 public User
User(
() { }
23
24 public User
User(
(long id
id)
) {
25 this.
this.id = id
id;
;
26 }
27
28 public User
User(
(String email,
email, String name)
name) {
29 this.email = email
this. email;
;
30 this.
this.name = name
name;
;
31 }
32
33 // Getter and setter methods
34 // ...
35
36 }
The Entity annotation mark this class as a JPA entity. The Table annotation speci es the db table’s name (would be “User” as default).
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 de nition!
Here there is the Dao class UserDao for our entity User :
src/main/java/netgloo/models/UserDao.java
1 package netgloo
netgloo..models
models;
;
2
3 // Imports ...
4
5 @Transactional
6 public interface UserDao extends CrudRepository
CrudRepository<
<User
User,
, Long
Long>
> {
7
8 /**
9 * This method will find an User instance in the database by its email.
10 * Note that this method is not implemented and its working code will be
11 * automagically generated from its signature by Spring Data JPA.
12 */
13 public User findByEmail
findByEmail(
(String email)
email);
14
15 }
blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 2/9
7/5/2019 Using MySQL in Spring Boot via Spring Data JPA and Hibernate – Netgloo Blog
See here for more details on how to create query from method names.
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
1 package netgloo
netgloo..controllers
controllers;
;
2
3 // Imports ...
4
5 @Controller
6 public class UserController {
7
8 /**
9 * GET /create --> Create a new user and save it in the database.
10 */
11 @RequestMapping(
@RequestMapping("/create"
"/create"))
12 @ResponseBody
13 public String create
create(
(String email,
email, String name)
name) {
14 String userId = ""
"";
;
15 try {
16 User user = new User
User((email
email,
, name
name)
);
17 userDao.
userDao.save
save(
(user
user));
18 userId = String
String.
.valueOf
valueOf((user
user.
.getId
getId(());
19 }
20 catch (Exception ex
ex)
) {
21 return "Error creating the user: " + exex..toString
toString(();
22 }
23 return "User succesfully created with id = " + userId
userId;;
24 }
25
26 /**
27 * GET /delete --> Delete the user having the passed id.
28 */
29 @RequestMapping(
@RequestMapping ("/delete"
"/delete"))
30 @ResponseBody
31 public String delete
delete(
(long id
id)) {
32 try {
33 User user = new User
User((id
id)
);
34 userDao.
userDao.delete
delete(
(user
user)
);
35 }
36 catch (Exception ex
ex)
) {
37 return "Error deleting the user:" + ex
ex.
.toString
toString(
();
38 }
39 return "User succesfully deleted!";
deleted!";
40 }
41
42 /**
43 * GET /get-by-email --> Return the id for the user having the passed
44 * email.
45 */
46 @RequestMapping("/get-by-email"
@RequestMapping("/get-by-email")
)
47 @ResponseBody
48 public String getByEmail
getByEmail(
(String email)
email) {
49 String userId = ""
"";
;
50 try {
51 User user = userDao
userDao..findByEmail
findByEmail(
(email
email)
);
52 userId = String
String.
.valueOf
valueOf(
(user
user.
.getId
getId(
());
53 }
54 catch (Exception ex
ex)
) {
55 return "User not found";
found";
56 }
57 return "The user id is: " + userId
userId;
;
58 }
59
60 /**
61 * GET /update --> Update the email and the name for the user in the
62 * database having the passed id.
63 */
64 @RequestMapping("/update"
@RequestMapping("/update")
)
65 @ResponseBody
66 public String updateUser
updateUser(
(long id
id,
, String email,
email, String name)
name) {
67 try {
68 User user = userDao
userDao..findOne
findOne(
(id
id)
);
69 user.setEmail
user.setEmail((email
email));
70 user.
user.setName
setName(
(name
name));
71 userDao.
userDao.save
save(
(user
user)
);
72 }
73 catch (Exception ex
ex)
) {
74 return "Error updating the user: " + ex
ex.
.toString
toString(
();
75 }
76 return "User succesfully updated!";
updated!";
blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 3/9
7/5/2019 Using MySQL in Spring Boot via Spring Data JPA and Hibernate – Netgloo Blog
77 }
78
79 // Private fields
80
81 @Autowired
82 private UserDao userDao;
userDao;
83
84 }
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 identi ed by the given id.
https://github.com/netgloo/spring-boot-samples/tree/master/spring-boot-mysql-springdatajpa-hibernate
References
http://spring.io/guides/gs/accessing-data-jpa/
http://docs.spring.io/spring-boot/docs/current/reference/html/howto-data-access.html
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html
http://www.petrikainulainen.net/programming/spring-framework/spring-data-jpa-tutorial-part-two-crud/
http://www.luckyryan.com/2013/02/20/spring-mvc-with-basic-persistence-spring-data-jpa-hibernate/
https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-jpa
62 Comments netgloo
1 Login
LOG IN WITH
OR SIGN UP WITH DISQUS ?
Name
blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 4/9
7/5/2019 Using MySQL in Spring Boot via Spring Data JPA and Hibernate – Netgloo Blog
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
2△ ▽ • Reply • Share ›
MB • 3 years ago
Thanks, in reply to your email I created the DB and everything works. Nice.
1△ ▽ • Reply • Share ›
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. ^_^
1△ ▽ • Reply • Share ›
blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 5/9
7/5/2019 Using MySQL in Spring Boot via Spring Data JPA and Hibernate – Netgloo Blog
If you have further questions or problem about this please use Stackoverflow.
△ ▽ • Reply • Share ›
Thanks for a simple sample. After typing all the files, I ran Application.java. Tomcat has started.
where TestSpringBoot is my project name. I tried removing the project name. Always I get this error :
thanks
Balaji
△ ▽ • Reply • Share ›
Field userDao in netgloo.controller.UserController required a bean of type 'netgloo.model.UserDao' that could not be
found.
△ ▽ • Reply • Share ›
blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 6/9
7/5/2019 Using MySQL in Spring Boot via Spring Data JPA and Hibernate – Netgloo Blog
Gradle:
2016-08-17 11:03:14.714 ERROR 5786 --- [ main] o.s.boot.SpringApplication : Application startup failed
△ ▽ • Reply • Share ›
MB • 3 years ago
I made no changes, but get
MySQLSyntaxErrorException: Unknown database 'netgloo_blog'
△ ▽ • Reply • Share ›
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.
△ ▽ • Reply • Share ›
blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 7/9
7/5/2019 Using MySQL in Spring Boot via Spring Data JPA and Hibernate – Netgloo Blog
Andrea Mod > John London • 4 years ago
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.
△ ▽ • Reply • Share ›
△ ▽ • Reply • Share ›
But it's better to use StackOverflow for these type of problems. Then you could post here the link to your
question.
△ ▽ • Reply • Share ›
ALSO ON NETGLOO
Installing Drush via Composer Spring Boot file upload with Ajax
1 comment • 3 years ago 43 comments • 4 years ago
Lenin Jose Meza Zarco — In CentOs 7, i need to install David — Hi.I have been trying to adapt your example as
Avatarphp-xml and create the symbolic link:$ sudo ln -s … Avatardescribed in: https://stackoverflow.com/q...but not be able.
…
Drupal 8: creating a custom Field Type Configuring GoDaddy’s shared hosting for Laravel 5
5 comments • 3 years ago and Git
Critter Power — How Do I add an image to this field? 32 comments • 4 years ago
Avatar Francis Claide Magallen — Hi, how about if I change my
Avatarremote production? how can I do that? for now I gotfatal:
remote production …
✉ Subscribe d Add Disqus to your siteAdd DisqusAdd 🔒 Disqus' Privacy PolicyPrivacy PolicyPrivacy
blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 8/9
7/5/2019 Using MySQL in Spring Boot via Spring Data JPA and Hibernate – Netgloo Blog
blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/ 9/9