springBoot03- springboot+jpa+thymeleaf增删改查

参考http://www.mooooc.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html 

项目结构:

1.模版下载:

http://start.spring.io/    在搜索框分别输入Web  Thymeleaf JPA MySQL, 下载的模版工程中就自动有这些依赖配置了

1.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.lch</groupId>
    <artifactId>springboot03</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.2.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>
        <!--本机安装的是jdk1.7,此处改为1.7,project Structure里的project SDK改为jdk1.7安装地址,
        settings下Java Compile下的target bytecode version也改为1.7,然后再更新maven项目即可
        view下tool windows,选择maven projects,在打开的maven 窗口点击刷新即可 -->
        <java.version>1.7</java.version>
    </properties>

    <dependencies>
        <!--下载模版项目时,选上Web Thymeleaf JPA MySQL,此处就自动有这些依赖配置了-->
        <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>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.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>

2. 

启动类添加Servlet的支持:继承SpringBootServletInitializer
package com.lch.springboot03;

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 Springboot03Application extends SpringBootServletInitializer{

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

    /**
     * 启动类添加Servlet的支持:继承SpringBootServletInitializer
     * alt+ Insert 选择对configure()方法进行重写
     * @return
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Springboot03Application.class);
    }
}

3.实体类 及 数据访问层接口定义

user.java

 1 package com.lch.springboot03.domain;
 2 
 3 import javax.persistence.*;
 4 
 5 /**
 6  * 实体类映射数据库表
 7  * 使用spring data jpa开发的时候,会将实体类中的成员变量与表中的字段一一对应,
 8  * 当我们在实体类中加上一个不与数据库表一一对应的成员变量的时候,此时我们只要在
 9  * 这个成员变量上加上注解@Transient
10  */
11 @Entity
12 public class User {
13     @Id
14     @GeneratedValue(strategy = GenerationType.AUTO)
15     private Long id;
16 
17     @Column(nullable = false)
18     private String password;
19     //name="username" 设置userName属性映射到数据库的username字段,而不是默认的user_name
20     @Column(name = "username", nullable = true, unique = true)
21     private String userName;
22 
23     @Column(nullable = true, unique = true)
24     private int age;
25 
26     public Long getId() {
27         return id;
28     }
29 
30     public void setId(Long id) {
31         this.id = id;
32     }
33 
34     public String getPassword() {
35         return password;
36     }
37 
38     public void setPassword(String password) {
39         this.password = password;
40     }
41 
42     public String getUserName() {
43         return userName;
44     }
45 
46     public void setUserName(String userName) {
47         this.userName = userName;
48     }
49 
50     public int getAge() {
51         return age;
52     }
53 
54     public void setAge(int age) {
55         this.age = age;
56     }
57 
58 
59 }
UserRepository
1 package com.lch.springboot03.repository;
2 
3 import com.lch.springboot03.domain.User;
4 import org.springframework.data.jpa.repository.JpaRepository;
5 public interface UserRepository extends JpaRepository<User,Long>{
6 
7     User findById(long id);
8     void deleteById(Long id);
9 }

4. service层

 1 package com.lch.springboot03.service;
 2 
 3 import com.lch.springboot03.domain.User;
 4 
 5 import java.util.List;
 6 
 7 public interface UserService {
 8     /**
 9      * 获取所有
10      *
11      * @return
12      */
13     public List<User> getUserList();
14 
15     /**
16      * 根据id获取
17      *
18      * @param id
19      * @return
20      */
21     public User findUserById(long id);
22 
23     /**
24      * 新增
25      *
26      * @param user
27      */
28     public void save(User user);
29 
30     /**
31      * 修改
32      *
33      * @param user
34      */
35     public void edit(User user);
36 
37     /**
38      * 删除
39      *
40      * @param id
41      */
42     public void delete(long id);
43 
44 
45 }
 1 package com.lch.springboot03.service;
 2 
 3 import com.lch.springboot03.domain.User;
 4 import com.lch.springboot03.repository.UserRepository;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Service;
 7 
 8 import java.util.List;
 9 @Service
10 public class UserServiceImpl implements UserService {
11 
12     @Autowired
13     private UserRepository userRepository;
14     @Override
15     public List<User> getUserList() {
16         return userRepository.findAll();
17     }
18 
19     @Override
20     public User findUserById(long id) {
21         return userRepository.findById(id);
22     }
23 
24     @Override
25     public void save(User user) {
26         userRepository.save(user);
27     }
28 
29     @Override
30     public void edit(User user) {
31         userRepository.save(user);
32     }
33 
34     @Override
35     public void delete(long id) {
36         userRepository.deleteById(id);
37     }
38 
39 
40 }

5.controller

 1 package com.lch.springboot03.controller;
 2 
 3 import com.lch.springboot03.domain.User;
 4 import com.lch.springboot03.service.UserService;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.ui.Model;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 
 9 import javax.annotation.Resource;
10 import java.util.List;
11 
12 @Controller
13 public class UserController {
14     @Resource
15     private UserService userService;
16     @RequestMapping("/")
17     public String index(){
18         return "redirect:/list"; //重定向到 /list
19     }
20 
21     @RequestMapping("/list")
22     public String lsit(Model model){
23         List<User> users = userService.getUserList();
24         model.addAttribute("users",users);
25         return "user/list"; // 跳转到springboot03\src\main\resources\templates\user下的list.html
26     }
27 
28     @RequestMapping("/toAdd")
29     public String toadd(User user){
30         return "user/userAdd";//跳转到userAdd.html
31     }
32 
33     @RequestMapping("/add")
34     public String add(User user){
35         userService.save(user);
36         return "redirect:/list";//添加完成,请求重定向到/list
37     }
38 
39     @RequestMapping("/toEdit")
40     public String toEdit(Model model,Long id){
41         User user = userService.findUserById(id);
42         model.addAttribute("user",user);
43         return "user/userEdit"; //跳转到userEdit.html页面
44     }
45     @RequestMapping("/edit")
46     public String edit(User user){
47         userService.edit(user);
48         return "redirect:/list";//获取列表数据并显示
49     }
50 
51     @RequestMapping("/delete")
52     public String edit(Long id){
53         userService.delete(id);
54         return "redirect:/list";
55     }
56 }

6. 前端页面:

在resources的statics目录下,建立css文件夹,把bootstrap.css拷贝进去。在templates目录下建user目录,下面建list.html,userAdd.html ,userEdit.html ,与controller中定义的对应

lsit.html

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8"/>
 5     <title>userList</title>
 6     <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
 7 </head>
 8 <body class="container">
 9 <br/>
10 <h1>用户列表</h1>
11 <br/><br/>
12 <div class="with:80%">
13     <table class="table table-hover">
14         <thead>
15         <tr>
16             <th>#</th>
17             <th>User Name</th>
18             <th>Password</th>
19             <th>Age</th>
20             <th>Edit</th>
21             <th>Delete</th>
22         </tr>
23         </thead>
24         <tbody>
25         <tr  th:each="user : ${users}">
26             <th scope="row" th:text="${user.id}">1</th>
27             <td th:text="${user.userName}">neo</td>
28             <td th:text="${user.password}">Otto</td>
29             <td th:text="${user.age}">6</td>
30             <td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td>
31             <td><a th:href="@{/delete(id=${user.id})}">delete</a></td>
32         </tr>
33         </tbody>
34     </table>
35 </div>
36 <div class="form-group">
37     <div class="col-sm-2 control-label">
38         <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
39     </div>
40 </div>
41 
42 </body>
43 </html>

userAdd.html 

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8"/>
 5     <title>user</title>
 6     <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
 7 </head>
 8 <body class="container">
 9 <br/>
10 <h1>添加用户</h1>
11 <br/><br/>
12 <div class="with:80%">
13     <form class="form-horizontal"   th:action="@{/add}"  method="post">
14         <div class="form-group">
15             <label for="userName" class="col-sm-2 control-label">userName</label>
16             <div class="col-sm-10">
17                 <input type="text" class="form-control" name="userName"  id="userName" placeholder="userName"/>
18             </div>
19         </div>
20         <div class="form-group">
21             <label for="password" class="col-sm-2 control-label" >Password</label>
22             <div class="col-sm-10">
23                 <input type="password" class="form-control" name="password" id="password" placeholder="Password"/>
24             </div>
25         </div>
26         <div class="form-group">
27             <label for="age" class="col-sm-2 control-label">age</label>
28             <div class="col-sm-10">
29                 <input type="text" class="form-control" name="age"  id="age" placeholder="age"/>
30             </div>
31         </div>
32         <div class="form-group">
33             <div class="col-sm-offset-2 col-sm-10">
34                 <input type="submit" value="Submit" class="btn btn-info" />
35                 &nbsp; &nbsp; &nbsp;
36                 <input type="reset" value="Reset" class="btn btn-info" />
37             </div>
38 
39         </div>
40     </form>
41 </div>
42 </body>
43 </html>

userEdit.html

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8"/>
 5     <title>user</title>
 6     <link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
 7 </head>
 8 <body class="container">
 9 <br/>
10 <h1>修改用户</h1>
11 <br/><br/>
12 <div class="with:80%">
13     <form class="form-horizontal"   th:action="@{/edit}" th:object="${user}"  method="post">
14         <input type="hidden" name="id" th:value="*{id}" />
15         <div class="form-group">
16             <label for="userName" class="col-sm-2 control-label">userName</label>
17             <div class="col-sm-10">
18                 <input type="text" class="form-control" name="userName"  id="userName" th:value="*{userName}" placeholder="userName"/>
19             </div>
20         </div>
21         <div class="form-group">
22             <label for="password" class="col-sm-2 control-label" >Password</label>
23             <div class="col-sm-10">
24                 <input type="password" class="form-control" name="password" id="password"  th:value="*{password}" placeholder="Password"/>
25             </div>
26         </div>
27         <div class="form-group">
28             <label for="age" class="col-sm-2 control-label">age</label>
29             <div class="col-sm-10">
30                 <input type="text" class="form-control" name="age"  id="age" th:value="*{age}" placeholder="age"/>
31             </div>
32         </div>
33         <div class="form-group">
34             <div class="col-sm-offset-2 col-sm-10">
35                 <input type="submit" value="Submit" class="btn btn-info" />
36                 &nbsp; &nbsp; &nbsp;
37                 <a href="/toAdd" th:href="@{/list}" class="btn btn-info">Back</a>
38             </div>
39 
40         </div>
41     </form>
42 </div>
43 </body>
44 </html>

7.数据库连接配置:

 1 spring.datasource.url=jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
 2 spring.datasource.username=root
 3 spring.datasource.password=root
 4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 5 
 6 spring.jpa.properties.hibernate.hbm2ddl.auto=update
 7 spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
 8 spring.jpa.show-sql= true
 9 #关闭thymeleaf的缓存,不然在开发过程中修改页面不会立刻生效需要重启,生产可配置为true
10 spring.thymeleaf.cache=false

8. 启动项目并访问:http://localhost:8080/list

点击add :

github 代码地址:

https://github.com/liuch0228/springboot.git

猜你喜欢

转载自www.cnblogs.com/enjoyjava/p/9064603.html