SpringBoot指南|第三篇:使用JPA访问MySQL数据库

本文介绍如何使用JPA来操作MySQL的CRUD。


目录

  • 1.简介
  • 2.环境准备
  • 3.使用Gradle构建项目
  • 4.创建MySQL数据库及相关配置文件
  • 5.构建JPA访问MySQL数据库
  • 6.参考资料
  • 7.结语

1.简介

这是SpringBoot指南的第三篇文章,关注公众号查看更多相关文章哦。

本文主要讲述如何使用JPA来操作MySQL进行CRUD(增查改删)。

2.环境准备

您需要:

· 15分钟左右

· IDEA开发工具

· JDK 1.8及以上

· Gradle 2.3及以上

3.使用Gradle构建项目

打开Idea -> new Project -> Spring Initializr -> Type选择Gradle Project -> 填写groupartifact -> 钩上webjpamysql -> 点下一步就行了。

依赖:

· web
    · web
· sql
    · jpa
    · mysql

注意:勾选依赖时,可以在搜索框中搜索相应的单词,如jpa,选中搜索结果即可。

如果是第一次构建Gradle项目,会弹出窗口让你选择是否创建Gradle的相关信息,选择ok即可,idea会自动帮我们下载最新的Gradle版本及相关的包,下载耗时较久,请耐心等待!!!

下载结束后Gradle会自动编译项目,然后会在idea右侧生成如下管理界面,类似Maven Projects:

gradle

最终生成build.gradle:

buildscript {
    ext {
        springBootVersion = '1.5.10.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    runtime('mysql:mysql-connector-java')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

下面我们开始创建数据库。

4.创建MySQL数据库及相关配置文件

首先,如果你已经有本地数据库,那么请略过以下文字,直接进入第二步mysql相关配置;

4.1:创建mysql数据库

因为楼主是使用mac电脑,所以下面就使用mac osx演示了。

首先,需要安装mysql,推荐mac的朋友们使用 brew install mysql 方式安装mysql;

如果想要使用安装包安装mysql的,可以到以下地址去下载mysql安装包,然后运行按提示安装即可:

https://dev.mysql.com/downloads/mysql/

下面演示如何使用 Homebrew 方式安装:

没有 Homebrew 的同学,官方地址:

https://brew.sh/

开始安装mysql数据库:

> brew info mysql // 此命令可以看到mysql安装时需要注意事项及相关信息,如版本等
> brew search mysql // 此命令用于搜索mysql,如果需要安装指定版本时可搜索后安装

// 如果出现如下提示,则表明mysql安装故障
==> Downloading https://homebrew.bintray.com/bottles/mysql-5.7.21.high_sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring mysql-5.7.21.high_sierra.bottle.tar.gz
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink share/man/man8/mysqld.8
/usr/local/share/man/man8 is not writable.

You can try again using:
  brew link mysql

// 此问题主要是因为没有权限导致, /usr/local/share/man/man8 is not writable. ,可使用如下命令解决

> sudo chown -R `whoami`:admin /usr/local/bin // whoami 可修改为当前登陆用户
> sudo chown -R `whoami`:admin /usr/local/share

执行完成后再次执行 brew link mysql 即可;

再之后需要对mysql进行初始化:

> mysql.server start 或者 brew services start mysql 启动mysql
> mysql_secure_installation // 如果不启动mysql,此命令报错

按初始化命令提示依次往下输入即可,依次为:

// 选择密码强度
There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG:

// 输入root密码,确认密码
Please set the password for root here.

New password:

Re-enter new password:

// 删除匿名用户
Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.

// 是否运行远程root登录,一般自己本地都是允许
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : no

 ... skipping.

// 删除测试数据库及权限
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

// 是否现在重新加载权限表
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.

// All done! 完成了

// 执行以下命令进入数据库
> mysql -u root -p

4.2:配置jpa+mysql

上面已经安装好mysql,现在我们来修改项目配置文件 application.properties

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/db_example
spring.datasource.username=root
spring.datasource.password=Yp_123456

第一行 spring.jpa.hibernate.ddl-auto 可以是noneupdatecreatecreate-drop

· `none` 这是MySQL的默认值,不会更改数据库结构。
· `update` Hibernate根据给定的Entity结构改变数据库。
· `create` 每次创建数据库,但在关闭时不要丢弃它。
· `create-drop` 创建数据库,然后在`SessionFactory`关闭时将其删除。

因为我们还没有数据库结构,所以我们从create开始。第一次运行后,我们可以根据程序要求将其切换为updatenone。当你想对数据库结构进行一些更改时使用update

注意事项:H2和其他嵌入式数据库的默认值是create-drop,但对于其他像MySQL这样的其他数据库则是none

下面我们开始编写业务代码。

5.构建JPA访问MySQL数据库

第一步:创建一个com.example.demo.User实体类,此类用于生成mysql表及接收浏览器输入内容,类如下:

package com.example.demo;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 * This tells Hibernate to make a table out of this class
 * 此类用于向mysql生成表
 *
 * @author yclimb
 * @date 2018/2/26
 */
@Entity
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String email;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

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


}

第二步:创建一个com.example.demo.UserRepository逻辑处理类,此类用于对mysql进行CRUD操作,类如下:

package com.example.demo;

import org.springframework.data.repository.CrudRepository;

/**
 * This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
 * 此类将被自动注入到一个名为userRepository的Bean中
 *
 * CRUD refers Create, Read, Update, Delete
 * CRUD指新增,查询,更新,删除
 *
 * @author yclimb
 * @date 2018/2/26
 */
public interface UserRepository extends CrudRepository<User, Long> {
    // 继承时范型<>中的对象及ID必填,否则类型出错
}

注意,此类核心重点在于继承CrudRepository接口,此接口作用是对特定数据库如mysql的通用CRUD操作,接口中提供了我们常用的一些增删改查方法等,有兴趣的同学可以看看源码。

package org.springframework.data.repository;

import java.io.Serializable;

/**
 * Interface for generic CRUD operations on a repository for a specific type.
 * 
 * @author Oliver Gierke
 * @author Eberhard Wolff
 */
@NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {

    /**
     * Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
     * entity instance completely.
     * 
     * @param entity
     * @return the saved entity
     */
    <S extends T> S save(S entity);

    /**
     * Saves all given entities.
     * 
     * @param entities
     * @return the saved entities
     * @throws IllegalArgumentException in case the given entity is {@literal null}.
     */
    <S extends T> Iterable<S> save(Iterable<S> entities);

    /**
     * Retrieves an entity by its id.
     * 
     * @param id must not be {@literal null}.
     * @return the entity with the given id or {@literal null} if none found
     * @throws IllegalArgumentException if {@code id} is {@literal null}
     */
    T findOne(ID id);

    /**
     * Returns whether an entity with the given id exists.
     * 
     * @param id must not be {@literal null}.
     * @return true if an entity with the given id exists, {@literal false} otherwise
     * @throws IllegalArgumentException if {@code id} is {@literal null}
     */
    boolean exists(ID id);

    /**
     * Returns all instances of the type.
     * 
     * @return all entities
     */
    Iterable<T> findAll();

    /**
     * Returns all instances of the type with the given IDs.
     * 
     * @param ids
     * @return
     */
    Iterable<T> findAll(Iterable<ID> ids);

    /**
     * Returns the number of entities available.
     * 
     * @return the number of entities
     */
    long count();

    /**
     * Deletes the entity with the given id.
     * 
     * @param id must not be {@literal null}.
     * @throws IllegalArgumentException in case the given {@code id} is {@literal null}
     */
    void delete(ID id);

    /**
     * Deletes a given entity.
     * 
     * @param entity
     * @throws IllegalArgumentException in case the given entity is {@literal null}.
     */
    void delete(T entity);

    /**
     * Deletes the given entities.
     * 
     * @param entities
     * @throws IllegalArgumentException in case the given {@link Iterable} is {@literal null}.
     */
    void delete(Iterable<? extends T> entities);

    /**
     * Deletes all entities managed by the repository.
     */
    void deleteAll();
}

第三步:创建一个com.example.demo.MainController控制器,用于处理浏览器url链接及传入数据及返回参数,代码如下:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * main controller
 *
 * @author yclimb
 * @date 2018/2/26
 */
@Controller    // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {

    @Autowired // This means to get the bean called userRepository
    private UserRepository userRepository; // 自动注入生成的对象,逻辑处理层

    /**
     * 新增用户方法
     * @param name 用户名
     * @param email 邮箱
     * @return str
     */
    @GetMapping(path="/add")
    public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody 返回的是响应字符串,而不是一个视图
        // @RequestParam GET或者POST请求参数

        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // 将返回一个JSON或者XML的用户组
        return userRepository.findAll();
    }
}

第三步:启动SpringBoot项目

因为我们使用Gradle,则可以使用./gradlew bootRun运行该应用程序。或者可以使用./gradlew构建构建JAR文件。然后你可以运行JAR文件:

java -jar build/libs/springboot-jpa-mysql-0.0.1-SNAPSHOT.jar

默认我们进入idea中com.example.demo.SpringbootJpaMysqlApplication启动类,右键选择“Run 'SpringbootJpaMysqlApplication'”即可。

第四步:运行项目,使用浏览器访问 http://127.0.0.1:8080/demo/all 可以查询默认JSON格式返回值;

get all

浏览器访问 http://127.0.0.1:8080/demo/add?name=first&email=yclimb@qq.com 新增一条记录,然后再次查询

add user

到此就已经OK了。

6.参考资料

本文源码:springboot-jpa-mysql

本文官方文档:Accessing data with MySQL

7.结语

到此本文就结束了,欢迎大家继续关注更多SpringBoot案例。

扫描下面二维码,关注我的公众号哦!!!


关注我的公众号


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 添加Maven依赖 在pom.xml文件添加以下Maven依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 2. 配置数据源 在application.properties文件添加以下配置: ``` spring.datasource.url=jdbc:mysql://localhost:3306/testdb spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 其,testdb为数据库名,root为用户名,password为密码。 3. 创建实体类 创建一个实体类,例如User: ``` @Entity @Table(name="user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String name; @Column(nullable = false) private Integer age; // getter和setter方法省略 } ``` 4. 创建DAO接口 创建一个DAO接口,例如UserRepository: ``` @Repository public interface UserRepository extends JpaRepository<User, Long> { } ``` 5. 编写业务逻辑 在业务逻辑使用UserRepository进行数据库操作,例如: ``` @Service public class UserService { @Autowired private UserRepository userRepository; public User addUser(User user) { return userRepository.save(user); } public User getUser(Long id) { return userRepository.findById(id).orElse(null); } public List<User> getAllUsers() { return userRepository.findAll(); } public void deleteUser(Long id) { userRepository.deleteById(id); } } ``` 注:@Repository和@Service注解分别表示该类是DAO接口和业务逻辑类。 6. 测试代码 编写测试代码,例如: ``` @RunWith(SpringRunner.class) @SpringBootTest public class UserServiceTest { @Autowired private UserService userService; @Test public void testAddUser() { User user = new User(); user.setName("张三"); user.setAge(20); User newUser = userService.addUser(user); assertNotNull(newUser.getId()); } @Test public void testGetUser() { User user = new User(); user.setName("李四"); user.setAge(25); User newUser = userService.addUser(user); Long id = newUser.getId(); User getUser = userService.getUser(id); assertEquals(getUser.getName(), "李四"); assertEquals(getUser.getAge(), Integer.valueOf(25)); } @Test public void testGetAllUsers() { List<User> users = userService.getAllUsers(); assertTrue(users.size() > 0); } @Test public void testDeleteUser() { User user = new User(); user.setName("王五"); user.setAge(30); User newUser = userService.addUser(user); Long id = newUser.getId(); userService.deleteUser(id); User getUser = userService.getUser(id); assertNull(getUser); } } ``` 注:@RunWith和@SpringBootTest注解分别表示使用JUnit运行测试和启用Spring Boot上下文进行测试。 以上就是Spring Boot访问mysql数据库的代码实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值