spring-boot JPA快速入门完整代码

spring-boot jpa 使用快速入门

项目结构

image.png

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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.toolz</groupId>
    <artifactId>myuser</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>myuser</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.6</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</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>
                <configuration>
                    <fork></fork>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

实体类entity代码

package com.toolz.myuser.entity;

import org.apache.commons.lang3.builder.ToStringBuilder;

import javax.persistence.*;
import java.util.Date;

@Entity
public class Userinfo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(nullable = false, unique = true)
    private String userName;

    @Column(nullable = false)
    private String pwd;

    @Column(nullable = false)
    private int age;

    @Column(nullable = false)
    private Date regTime;

    public long getId(){
        return id;
    }

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

    public String getUserName(){
        return userName;
    }

    public void setUserName(String userName){
        this.userName = userName;
    }
    public String getPwd(){
        return pwd;
    }

    public void setPwd(String pwd){
        this.pwd = pwd;
    }
    public int getAge(){
        return age;
    }

    public void setAge(int age){
        this.age = age;
    }

    public Date getRegTime(){
        return regTime;
    }

    public void setRegTime(Date regTime){
        this.regTime = regTime;
    }

    @Override
    public String toString(){
        return ToStringBuilder.reflectionToString(this);
    }
}

Application类

package com.toolz.myuser;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class MyuserApplication extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(MyuserApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(MyuserApplication.class, args);
    }

}

Controller

package com.toolz.myuser.controller;

import com.toolz.myuser.entity.Userinfo;
import com.toolz.myuser.param.UserParam;
import com.toolz.myuser.repository.UserRepository;
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.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;


@Controller
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/")
    public String index(){return "redirect:/list";}

    @RequestMapping("/list")
    public String list(Model model, @RequestParam(value="page", defaultValue = "0") Integer page,
                       @RequestParam(value = "size", defaultValue = "10") Integer size){
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(page, size);
        Page<Userinfo> userList = userRepository.findList(pageable);
        model.addAttribute("users",userList);
        return "user/list";
    }

    @RequestMapping("toAdd")
    public String toAdd(){return "user/userAdd";}

    @RequestMapping("/add")
    public String add(UserParam userParam, BindingResult result, ModelMap model)
    {
        String errorMsg = "";
        if (result.hasErrors())
        {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError e: list){
                errorMsg = errorMsg + e.getCode() + ":" + e.getDefaultMessage();
            }
            model.addAttribute("errorMsg", errorMsg);
            return "user/userAdd";
        }
        Userinfo u = userRepository.findByUserName(userParam.getUserName());
        if(u!=null)
        {
            model.addAttribute("errorMsg", "用户名已存在");
            return "user/userAdd";
        }
        Userinfo user = new Userinfo();
        BeanUtils.copyProperties(userParam, user);
        user.setRegTime(new Date());
        userRepository.save(user);
        return "redirect:/list";
    }

    @RequestMapping("/delete")
    public String del(Long id){
        userRepository.deleteById(id);
        return "redirect:/list";
    }

    @RequestMapping("toEdit")
    public String edit(Long id){

        return "user/userAdd";
    }
}

DAO

package com.toolz.myuser.repository;

import com.toolz.myuser.entity.Userinfo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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.CrudRepository;

import javax.transaction.Transactional;
import java.util.Optional;


public interface UserRepository extends JpaRepository<Userinfo, Long> {

    @Query("select u from Userinfo u")
    Page<Userinfo> findList(Pageable pageable);

    @Override
    Optional<Userinfo> findById(Long id);

    // 简单自定义查询
    Userinfo findByUserName(String userName);

    void deleteById(Long id);

    @Modifying
    @Transactional
    @Query(value ="delete from Userinfo u where u.userName = ?1")
    void deleteByUserName(String userName);

}

Param

package com.toolz.myuser.param;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;

public class UserParam {

    private long id;

    @NotEmpty(message = "用户名不能为空")
    private String userName;

    @NotEmpty(message = "用户名不能为空")
    @Length(message = "密码长度不能少于6位")
    private String pwd;

    @Max(value = 100, message = "年龄不能大于100")
    @Min(value = 1, message = "年龄必须大于1")
    private int age;

    public long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

重写的启动类

package com.toolz.myuser;

import com.toolz.myuser.entity.Userinfo;
import com.toolz.myuser.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.Date;

@Profile(value = "dev")
@Component
public class MyStartupRunner implements CommandLineRunner {
    @Autowired
    private UserRepository userRepository;

    private String addUser(Userinfo user){
        String name = "zhangsan";
        String pwd = "abc";
        int age = 18;

        Userinfo u = userRepository.findByUserName(name);
        if(u!=null)
        {
            System.out.println("该用户已存在");
            userRepository.deleteByUserName(name);
            System.out.println("该用户已被清除");
        }

        user.setUserName(name);
        user.setPwd(pwd);
        user.setAge(age);
        user.setRegTime(new Date());
        userRepository.save(user);
        return  "用户保存成功";

    }

    public void run(String... strings) throws Exception {
        System.out.println("项目启动了!!!!!!!!!!!!!!!!!!!!!!");

        System.out.println("开始添加用户");
        String res = addUser(new Userinfo());
        System.out.println(res);
    }
}

配置文件
application.properties


# 自动创建/更新/验证数据库表结构
spring.jpa.properties.hibernate.hbm2ddl.auto = update
# 设置数据库引擎为innodb
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
# 终端输出sql语句
spring.jpa.show-sql=true

# 开发为false
spring.thymeleaf.cache=false

#server.port=8080

spring.profiles.active=dev

application-dev.properties

spring.datasource.url = jdbc:mysql://127.0.0.1:3306/user?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

server.port=8081

list.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
</head>
<body class="container">

    <h1>用户列表</h1>
    <br/>
<div class="width:80%">
    <table class="table table-hover">
        <thead>
            <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>密码</th>
                <th>年龄</th>
                <th>注册时间</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
        <tr th:each ="u:${users}">
            <td scope="row" th:text="${u.id}">1111</td>
            <td th:text="${u.userName}">Wayne</td>
            <td th:text="${u.pwd}">abcabcabc</td>
            <td th:text="${u.age}">120</td>
            <td th:text="${u.regTime}">2018/12/27</td>
            <td><a th:href="@{/toEdit(id=${u.id})}">编辑</a></td>
            <td><a th:href="@{/delete(id=${u.id})}" onclick="return confirm('确认删除该用户吗?')">删除</a></td>
        </tr>
        </tbody>
    </table>
</div>
<div class="form-group">
    <div class="col-sm-2 control-label">
        <a href="/toAdd" class="btn btn-info">添加</a>
    </div>
</div>
</body>
</html>

userAdd.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
</head>
<body class="container">
    <h1>添加用户</h1>
    <br/>

    <form th:action="@{/add}" method="post" class="form-horizontal">
        <div class="form-group">
            <label for="userName" class="col-sm-2 control-label">用户名</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="userName" id="userName" placeholder="用户名">
            </div>
        </div>
        <div class="form-group">
            <label for="userName" class="col-sm-2 control-label">密码</label>
            <div class="col-sm-10">
                <input type="password" class="form-control" name="pwd" id="pwd" placeholder="密码">
            </div>
        </div>
        <div class="form-group">
            <label for="userName" class="col-sm-2 control-label">年龄</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="age" id="age" placeholder="年龄">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-10">
                <div th:if="${errorMsg!=null}" class="alert alert-danger" role="alert" th:text="${errorMsg}">

                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" value="添加" class="btn btn-info">
                <input type="reset" value="重置" class="btn btn-info">
                <a th:href="@{/list}">后退</a>
            </div>
        </div>
    </form>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 201,552评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,666评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,519评论 0 334
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,180评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,205评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,344评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,781评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,449评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,635评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,467评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,515评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,217评论 3 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,775评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,851评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,084评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,637评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,204评论 2 341

推荐阅读更多精彩内容