使用SpringBoot+JPA的简单案例

简介:

JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

第一步:引入我们需要的POM文件

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.5.1.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
</dependencies>

第二步:配置application.yml文件

server:
port: 8080
spring:
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
show-sql: true
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root

第三步:创建一个简单的工具类ResponseResult

package com.feicheng.common;

/**
* 结果返回集
* @author Lenovo
*/
public class ResponseResult {

private Integer code;

private String msg;

public void setCode(Integer code) {
this.code = code;
}

public void setMsg(String msg) {
this.msg = msg;
}

public Integer getCode() {
return code;
}

public String getMsg() {
return msg;
}

public ResponseResult(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}

第四步:创建一个test数据库和创建一个user表(字段有:id,username)

CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET latin1 */;

USE `test`;

/*Table structure for table `user` */

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`password` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;

第五步:创建实体类User

package com.feicheng.entity;
import javax.persistence.*;
/**
* @author Lenovo
*/
@Table(name = "user")
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

private String name;

private String password;

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 getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}

第六步:创建UserController

package com.feicheng.controller;

import com.feicheng.common.ResponseResult;
import com.feicheng.entity.User;
import com.feicheng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collections;
import java.util.List;

/**
* @author Lenovo
*/
@Controller
@RequestMapping("user")
public class UserController {

@Autowired
private UserService userService;

/**
* 查询全部用户
*
* @return
*/
@GetMapping("list")
public ResponseEntity<List<User>> list() {

List<User> users = this.userService.select();

if (CollectionUtils.isEmpty(users)) {

return ResponseEntity.notFound().build();
}

return ResponseEntity.ok(users);
}

/**
* 根据用户名查询用户
*
* @param userName
* @return
*/
@GetMapping("select/{userName}")
public ResponseEntity<User> selectUserByName(@PathVariable("userName") String userName) {

User user = this.userService.selectUserByName(userName);

if (user == null) {

return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}

return ResponseEntity.ok(user);
}

/**
* 根据id修改用户
*
* @param user
* @return
*/
@PostMapping("edit")
public ResponseEntity<ResponseResult> edit(User user) {

ResponseResult responseResult = this.userService.edit(user);

return ResponseEntity.ok(responseResult);
}

/**
* 根据id删除用户
*
* @param id
* @return
*/
@PostMapping("delete/{id}")
public ResponseEntity<ResponseResult> delete(@PathVariable("id") Integer id) {

ResponseResult responseResult = this.userService.delete(id);

return ResponseEntity.ok(responseResult);
}
}

第七步:创建UserService

package com.feicheng.service;

import com.feicheng.common.ResponseResult;
import com.feicheng.entity.User;

import java.util.List;

/**
* @author Lenovo
*/
public interface UserService {

// 查询全部用户
List<User> select();

// 根据用户名查询用户信息
User selectUserByName(String userName);

// 根据用户id修改用户
ResponseResult edit(User user);

// 根据id删除用户
ResponseResult delete(Integer id);
}

第八步:创建UserServiceImpl

package com.feicheng.service.impl;

import com.feicheng.common.ResponseResult;
import com.feicheng.entity.User;
import com.feicheng.repository.UserRepository;
import com.feicheng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

/**
* @author Lenovo
*/
@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;

/**
* 查询全部用户
*
* @return
*/
@Override
public List<User> select() {

List<User> users = this.userRepository.findAll();

if (CollectionUtils.isEmpty(users)) {

return null;
}

return users;
}

/**
* 根据用户名查询用户信息
*
* @param userName
* @return
*/
@Override
public User selectUserByName(String userName) {

User user = new User();

user.setName(userName);

Example<User> example = Example.of(user);

Optional<User> one = this.userRepository.findOne(example);

user = one.get();

return user;
}

/**
* 根据用户id修改用户信息
*
* @param user
* @return
*/
@Override
public ResponseResult edit(User user) {

Integer count = this.userRepository.edit(user.getName(), user.getPassword(), user.getId());

if (count > 0) {

return new ResponseResult(200, "修改成功");

}

return new ResponseResult(500, "修改失败");
}

/**
* 根据id删除用户
*
* @param id
* @return
*/
@Override
@Transactional
public ResponseResult delete(Integer id) {

try {

this.userRepository.deleteById(id);

return new ResponseResult(200, "删除成功");

} catch (Exception e) {

e.printStackTrace();

return new ResponseResult(500, "删除失败");
}
}
}

第九步:创建UserRepository

package com.feicheng.repository;

import com.feicheng.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
* @author Lenovo
*/
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {

@Modifying
@Transactional
@Query("update User u set u.name = :name, u.password = :password where u.id = :id")
Integer edit(@Param("name") String name, @Param("password") String password, @Param("id") Integer id);
}

最后总结:

使用JPA操作数据库比较方便,把我们想要的代码都封装好了
操作起来还是比较简单快捷,容易上手

想继续了解JPA,可以去我的GitHub上做的一个权限管理系统,就是用的JPA来操作的数据库

GitHub地址:https://github.com/javaenigneer/authority-system