上一節,已經使用Spring Boot實現了一個restful api,可是數據的交互是經過map實現的,那麼本節咱們使用jpa與數據庫進行交互,本節完成後,能夠結合以前的demo實現一個更加複雜的demo。
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
spring: jpa: hibernate: ddl-auto: update datasource: druid: url: jdbc:mysql://127.0.0.1:3306/blog?useUnicode=true&characterEncoding=UTF8&useSSL=false username: root password: root jpa: show-sql: true
package cn.sockstack.blog.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import javax.persistence.*; import java.io.Serializable; import java.util.Date; import java.util.List; @Entity @Data @Table(name = "users") public class User implements Serializable { @Id @GeneratedValue private Integer id; @Column(nullable = false, columnDefinition = "varchar(20)") private String account; @Column(nullable = false, columnDefinition = "varchar(32)") private String password; @Column(nullable = true, columnDefinition = "varchar(128) default ''") private String name; @Column(nullable = false, columnDefinition = "tinyint(1)") private Integer isForbidden; @Column(nullable = true, columnDefinition = "varchar(15) default ''") private String ip; @Temporal(TemporalType.TIMESTAMP) private Date createdAt; @Temporal(TemporalType.TIMESTAMP) private Date updatedAt; @Temporal(TemporalType.TIMESTAMP) private Date deletedAt; @Column(nullable = true, columnDefinition = "int(11)") private Integer deletedUserId; @JsonIgnore @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Article> articles; }
package cn.sockstack.blog.dao; import cn.sockstack.blog.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository public interface UserDao extends JpaRepository<User, Integer>, PagingAndSortingRepository<User, Integer> { }
package cn.sockstack.blog.services; import cn.sockstack.blog.common.exception.LoginFailException; import cn.sockstack.blog.dto.UserDto; import cn.sockstack.blog.entity.User; import org.springframework.data.domain.Page; import java.util.List; public interface IUserService { /** * 增長用戶 * @param userDto * @return */ User addUser(UserDto userDto); /** * 修改用戶信息 * @param userDto * @return */ User updateUser(UserDto userDto); /** * 物理刪除用戶 * @param user_id * @return */ void deleteUser(Integer user_id); /** * 邏輯刪除用戶 * @param user_id * @return */ User removeUser(Integer user_id, Integer delete_admin_id); /** * 查詢用戶 * @param userDto * @return */ List<User> query(UserDto userDto); /** * 獲取一個用戶的信息 * @param user_id * @return */ User getOne(Integer user_id); /** * 獲取全部的用戶 * @param page * @param pagesize * @return */ Page<User> getAll(Integer page, Integer pagesize); /** * 登陸 * @param userDto * @return */ User doLogin(UserDto userDto) throws LoginFailException; }
package cn.sockstack.blog.services.impl; import cn.sockstack.blog.common.exception.LoginFailException; import cn.sockstack.blog.common.utils.CommonUtil; import cn.sockstack.blog.dao.UserDao; import cn.sockstack.blog.dto.UserDto; import cn.sockstack.blog.entity.User; import cn.sockstack.blog.services.IUserService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; import java.util.Optional; @Service public class UserServiceImpl implements IUserService { @Autowired UserDao userDao; @Override public User addUser(UserDto userDto) { String password = CommonUtil.string2Md5(userDto.getPassword()); userDto.setPassword(password); User user = new User(); BeanUtils.copyProperties(userDto, user); user.setIsForbidden(0); user.setCreatedAt(new Date()); user = userDao.save(user); user = CommonUtil.hidePassword(user); return user; } @Override public User updateUser(UserDto userDto) { return null; } @Override public void deleteUser(Integer user_id) { userDao.deleteById(user_id);; } @Override public User removeUser(Integer user_id, Integer delete_admin_id) { Optional<User> userOpt = userDao.findById(user_id); User user = userOpt.get(); user.setDeletedAt(new Date()); user = userDao.save(user); user = CommonUtil.hidePassword(user); return user; } @Override public List<User> query(UserDto userDto) { return null; } @Override public User getOne(Integer user_id) { User user = userDao.findByIdAndDeletedUserIdIsNull(user_id); user = CommonUtil.hidePassword(user); return user; } @Override public Page<User> getAll(Integer page, Integer pagesize) { PageRequest pageRequest = PageRequest.of(page, pagesize); return userDao.findAll(pageRequest); } @Override public User doLogin(UserDto userDto) throws LoginFailException { String password = CommonUtil.string2Md5(userDto.getPassword()); String account = userDto.getAccount(); User user = userDao.findByAccountAndPassword(account, password); if (user == null) { throw new LoginFailException("帳號或者密碼錯誤"); } user = CommonUtil.hidePassword(user); user.setIp(CommonUtil.getClientIp()); return user; } }
package cn.sockstack.blog.web; import cn.sockstack.blog.common.RestResponseBody; import cn.sockstack.blog.common.enums.HttpStatus; import cn.sockstack.blog.common.exception.LoginFailException; import cn.sockstack.blog.common.utils.JwtUtil; import cn.sockstack.blog.dto.UserDto; import cn.sockstack.blog.entity.User; import cn.sockstack.blog.form.AddUserForm; import cn.sockstack.blog.form.LoginForm; import cn.sockstack.blog.services.IUserService; import cn.sockstack.blog.vo.UserVo; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; @RestController @RequestMapping("/users") public class UsersController { @Autowired IUserService userService; @GetMapping("") public Page<User> getOne(@RequestParam(name = "page", defaultValue = "1", required = false) Integer page, @RequestParam(name = "pagesize", defaultValue = "20", required = false) Integer pagesize) { if ((page = page - 1) < 0){ page = 0; } return userService.getAll(page, pagesize); } @PostMapping("") public User addUser(@Valid AddUserForm addUserForm, UserDto userDto) { BeanUtils.copyProperties(addUserForm, userDto); return userService.addUser(userDto); } @GetMapping("/{id}") public RestResponseBody<User> getOne(@PathVariable(name = "id", required = true) Integer id) { User user = userService.getOne(id); return new RestResponseBody<>(HttpStatus.REQUEST_SUCCESS.Status(), HttpStatus.REQUEST_SUCCESS.Message(), user); } @DeleteMapping("/{id}") public RestResponseBody<User> removeUser(@PathVariable(name = "id", required = true) Integer id) { User user = userService.removeUser(id, 1); return new RestResponseBody<>(HttpStatus.REQUEST_SUCCESS.Status(), HttpStatus.REQUEST_SUCCESS.Message(), user); } @PostMapping("/login") public RestResponseBody<UserVo> doLogin(@Valid LoginForm loginForm, UserDto userDto, UserVo userVo, HttpServletRequest request) { BeanUtils.copyProperties(loginForm, userDto); User user = userService.doLogin(userDto); BeanUtils.copyProperties(user, userVo); String token = JwtUtil.crypt(3600, user); userVo.setToken(token); return new RestResponseBody<>(HttpStatus.REQUEST_SUCCESS.Status(), HttpStatus.REQUEST_SUCCESS.Message(), userVo); } @PostMapping("/register") public RestResponseBody<String> doRegister() { return null; } }
經過postman進行測試便可。java
有部分的內容沒有貼出來,可是不影響代碼的閱讀。mysql
更多精彩文章,請關注個人博客 SOCKSTACK,分享個人工做經驗。