SpringBoot基本操作(三)——SpringBoot整合SpringDataJpa(有demo)

SpringBoot2.0笔记

(一)SpringBoot基本操作——环境搭建及项目创建(有demo)

(二)SpringBoot基本操作——使用IDEA打war包发布及测试

(三)SpringBoot基本操作——SpringBoot整合SpringDataJpa(有demo)

(四)SpringBoot基本操作——SpringBoot使用RedisTemplate整合Redis(有demo)

(五)SpringBoot基本操作——SpringBoot使用Jedis整合Redis(有demo)

(六)SpringBoot基本操作——SpringBoot使用Junit4单元测试(有demo)

(七)SpringBoot基本操作——SpringBoot整合Shiro权限管理(完整demo+界面)

 

注:本篇完成对用户对象的表生成,以及最基本的CRUD(增删改查)操作,demo可直接下载按照readme给出的链接测试

本文使用idea工具构建Springboot2.0+SpringMvc+Thymeleaf+SpringDataJPA+MySql项目

GitHub地址:https://github.com/jwwam/springbootJpa.git

一、编写整合代码

1.新建User实体,生成用户表

由于我们引入了lombok,所以直接使用@Data注解会自动帮我们生成对应的get/set以及toString方法,无需再手动编写。编写BaseEntity是基本操作,通过继承方便我们使用公共字段。

User.java

package com.springboot.demo.entity;

import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

/**
 * @ClassName: User
 * @Auther: zhangyingqi
 * @Date: 2018/8/27 17:17
 * @Description:
 */
@Entity
@Table(name = "user")
@Data
public class User extends BaseEntity{
    @Column(name = "name", length = 100)
    private String name;

    @Column(name = "age")
    private int age;
}

BaseEntity.java

package com.springboot.demo.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import org.hibernate.annotations.GenericGenerator;

@MappedSuperclass
public class BaseEntity {
    @Id
    //@GeneratedValue(strategy = GenerationType.AUTO)
    @GenericGenerator(name = "uuid", strategy = "uuid")
    protected String id;

    @Column(name= "create_date") //创建时间
    Date createDate = new Date();

    @Column(name= "update_date")//修改时间
    Date updateDate;

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }

	public String getId() {
		return id;
	}

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



}

2.编写service接口及实现

UserService.java

其中包含增删改查部分的接口

package com.springboot.demo.service;

import com.springboot.demo.entity.User;

import java.util.List;

public interface UserService {
    User save(User user);

    User findById(String id);

    void delete(User user);

    List<User> findAll();
}

UserServiceImpl.java

package com.springboot.demo.service.impl;

import com.springboot.demo.dao.UserDao;
import com.springboot.demo.entity.User;
import com.springboot.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName: UserServiceImpl
 * @Auther: zhangyingqi
 * @Date: 2018/8/27 17:26
 * @Description:
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService{
    @Autowired
    UserDao userDao;

    @Override
    public User save(User user) {
        return userDao.save(user);
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    public void delete(User user) {
        userDao.delete(user);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }
}

3.编写具体的持久化Dao层操作

UserDao.java

由于jpa会自动解析方法名,因此像通过id查找对象只需写明findById,表示通过id去检索数据,其他字段一样。

另外我们通过继承jpa原生接口可以获取很多方法,无需再自己去编写具体的SQL语句

package com.springboot.demo.dao;

import com.springboot.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public interface UserDao extends PagingAndSortingRepository<User, Long>,JpaSpecificationExecutor<User>,JpaRepository<User,Long> {
    User findById(String id);
}

4.编写业务逻辑Controller层代码

UserController.java

package com.springboot.demo.controller;

import com.springboot.demo.base.controller.BaseController;
import com.springboot.demo.base.utils.StateParameter;
import com.springboot.demo.entity.User;
import com.springboot.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: UserController
 * @Auther: zhangyingqi
 * @Date: 2018/8/27 17:30
 * @Description:
 */
@Controller
@RequestMapping(value="/user")
public class UserController extends BaseController{
    @Autowired
    UserService userService;

    /**
     * @auther: zhangyingqi
     * @date: 17:37 2018/8/27
     * @param: [request, user]
     * @return: org.springframework.ui.ModelMap
     * @Description: 用户保存&更新
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap add(User user){
        try {
            if(StringUtils.isEmpty(user.getId())){
                user.setId(getUuid());
            }else{
                user.setUpdateDate(new Date());
            }
            userService.save(user);
            logger.info("保存成功");
            return getModelMap(StateParameter.SUCCESS, user, "保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return getModelMap(StateParameter.FAULT, null, "保存失败");
        }
    }

    /**
     * @auther: zhangyingqi
     * @date: 17:47 2018/8/27
     * @param: [id]
     * @return: org.springframework.ui.ModelMap
     * @Description: 删除用户
     */
    @RequestMapping(value="/delete", method = RequestMethod.GET)
    @ResponseBody
    public ModelMap delete(String id){
        try {
            User user = userService.findById(id);
            if(user==null){
                return getModelMap(StateParameter.FAULT, user, "找不到该用户");
            }
            userService.delete(user);
            logger.info("删除成功");
            return getModelMap(StateParameter.SUCCESS, null, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return getModelMap(StateParameter.FAULT, null, "删除失败");
        }
    }

    /**
     * @auther: zhangyingqi
     * @date: 17:47 2018/8/27
     * @param: [request]
     * @return: java.lang.String
     * @Description: 查询用户列表
     */
    @RequestMapping(value="/list")
    public String view(HttpServletRequest request){
        List<User> list = userService.findAll();
        request.setAttribute("list", list);
        logger.info("返回列表页面");
        return "/demoPage/listPage";
    }

}

到此看下目录结构,还差一个列表界面

5.添加查看列表页面

listPage.html

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
    <div>
        <table style="border: solid 1px #aaaaaa;">
            <thead>
                <tr>
                    <th>用户名称</th>
                    <th>年龄</th>
                    <th>创建时间</th>
                </tr>
            </thead>
            <tbody>
                <tr th:if="${list !=null}" th:each="item : ${list}">
                    <td th:text="${item.name}"></td>
                    <td th:text="${item.age}"></td>
                    <td th:text="${#dates.format(item.createDate, 'yyyy-MM-dd')}"></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

至此所有的准备工作完成,接下来我们测试一下。

二、启动测试

1.添加&更新数据

发送post请求:http://localhost:8080/user/add?name=老王&age=25

其实这里实质还是get请求只为了方便测试,为了不使用明文传参,实际当中我们基本都是通过form表单或者Ajax使用Post请求来提交数据,所以后台我使用Post接收。

返回保存成功,查看数据库新增了一条数据。

2.数据更新

我们直接上传已经存在的记录,jpa就会更新而不会重新添加,很方便,下面的记录显示了更新时间说明数据被更新成功了,

name字段值由“老王”更新为“老王的儿子”。

3.数据删除

4.查看数据列表

暂时不包含分页,具体的分页我会在后续的文章中详细介绍请关注。查询列表:http://localhost:8080/user/list

补一个pom包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.springboot</groupId>
	<artifactId>springbootJpa</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>springbootJpa</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.4.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<!--<scope>provided</scope>-->
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.hibernate</groupId>
					<artifactId>hibernate-entitymanager</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.hibernate</groupId>
					<artifactId>hibernate-core</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>5.2.10.Final</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

全文完,2018/8/28

写博文不易,转载请注明出处。

 

 

 

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页