Springboot-mybatis realizes addition, deletion, modification and query (2)

2. Realize paging display and query of user list

Before starting, add a log configuration to the yml configuration file to print the sql statement we executed.

logging:
  file:
    name: log/log.log
  level:
    root: info
    lzy.springbootuser: debug
  1. Define the UserDao interface (new interface) in the dao layer
    to implement user addition, deletion, modification, and query operations.
    To hand over the interface to mybatis for management, you need to add an annotation here @Mapperto tell springboot that this is a mybatis mapper class.
    In this case, the namespace of the xml file under the mybatis folder can directly use this interface.
    Then add an @Repositoryinterface to hand over userdao to the spring container management, and then use annotations to inject directly when calling the dao layer in the service layer.
    Then you can define methods in UserDao.
    insert image description here
    Note: The list and User will be marked in red here, because the Java package needs to be imported, and you can see it by placing the mouse on the red one. You can also use alt+enter.
@Mapper  //用来告诉springboot这是一个mybatis的mapper类
@Repository  //将userdao交由spring容器管理
public interface UserDao {
    
    
	//	查询所有用户
	public List<User> listUser(); //返回一个list集合。方法名:listUser

	//根据用户名查询用户并分页展示
	public List<User> listUserByName();
}

If you want to realize the paging function here, you need to use some parameters, build a query package under the pojo entity class, create a UserQuery entity class in the query package, and encapsulate all the things that need to be queried into this entity class.

public class UserQuery {
    
    
	private Integer pageNum = 1; //定义一个pageNum,当前页面,定义为1.
	private Integer pageSize = 2; //每页所显示的数据条数
	private String name; //根据用户名查询
}

insert image description here
Then hand it over to Lombok to manage

@Data
@AllArgsConstructor
@NoArgsConstructor

That is,
insert image description here
at this point, the method has been defined, and the parameters are passed into the UserDao method.

public interface UserDao {
    
    
	//	查询所有用户
	public List<User> listUser(); //返回一个list集合。方法名:listUser

	//根据用户名查询用户并分页展示
	public List<User> listUserByName(UserQuery userQuery);
}

The interface is defined.

  1. Create an xml file under resources/mybatis to implement the operation on the data table that you want to implement in the interface.
    Create a new UserMapper.xml file and write sql statements.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="lzy.springbootuser.dao.UserDao">
    <!--已经在UserDao里加了@mapper注解,所以这里的namespace才能找到
    namespace是绑定接口的作用-->
    <!--下面就实现方法-->
    <select id="listUser" resultType="lzy.springbootuser.pojo.User">
        select *
        from mybatis.user;
    </select>
    
    <select id="listUserByName" parameterType="lzy.springbootuser.pojo.query.UserQuery" resultType="lzy.springbootuser.pojo.User">
        select *
        from mybatis.user
        <where>
            <if test="name != null and name != ''">
                and 'name' like concat('%',#{
    
    name},'%')
            </if>
        </where>
    </select>
<!--    #{
    
    }在括号里填属性后,这样能直接取到该属性-->
<!--    这里用到的where动态判定-->
<!--    concat为连接函数,把多个字符连接起来-->
</mapper>
  1. Then you need to start writing the service layer.
    Create a new UserService interface (new Interface)
    The method in the UserService interface is the same as that in the dao layer, but here the paging display is not a list collection, but PageInfo. If you want to use it, you first need to introduce dependencies in the pom.xml file.
		<!--分页-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>

Next, create a new UserService implementation class (new class) UserServiceImpl in the service layer.
Let him realize implements our UserService interface and rewrite his method.
insert image description here
After selecting this rewriting method, the following will be automatically available:
insert image description here

The dao layer needs to be referenced in the service layer, using @Serviceannotations.
Then inject the UserDao layer in the class:

@Autowired
	private UserDao userDao;

An arrow appears on the left, click it to go to the calling place in the dao layer,
insert image description here
and then you can directly call the method of the dao layer.
Modify the parameters returned by listUser and modify null:

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

The second query method needs to start PageHelper first, and then write the obtained parameters:

	@Override
	public PageInfo<User> listUserByName(UserQuery userQuery) {
    
    
		PageHelper.startPage(userQuery.getPageNum(),userQuery.getPageSize());
		return new PageInfo<User>(userDao.listUserByName(userQuery));
	}

Interfaces and methods are defined

  1. The controller layer controls the view jump.
    Create a new (new class) UserController
    and add @Controllerannotations
    insert image description here
    , and then inject the service layer into the controller layer:
@Controller
public class UserController {
    
    
	@Autowired
	private UserService userService;
}

To write the view later, you need a home page, create a new index.html page under resource/templates, and then control the jump, you need to introduce a dependency in the pom file:

	  <!--控制页面跳转-->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>

Then write the method in UserController:

	@GetMapping("/")  //用来设置一个地址
	public String index(){
    
    
		return "index";  //定义跳转到index页面
	}

Ctrl + mouse click on the index will jump to the index.html page.
You can run the code here to see if you can get this html page. I have an error at runtime:
insert image description here
the solution found on the Internet: the bug that appears probably means: relying on circular references is discouraged, and it is prohibited by default. Update your application to remove dependency cycles between beans. As a last resort, loops can be automatically broken by setting spring.main.allow-circular-references to true.
Add in the configuration file yml

spring:
  main:
    allow-circular-references: true

Then just fine, after running, there is an index page
insert image description here

  1. The front-end page (here is the web page of the Java-Web project, not the front-end part separated from the front-end and back-end). The
    original tutorial uses a Semantic-ui here. The official document link https://semantic-ui.com
    is a CSS framework.
    The style is imported by the online CDN method:
    insert image description here
    paste it into our html page <head>. Then the JavaScript introduced here is based on jquery, check the jquery cdn on Baidu.
    There is a problem here: the official cdn is used, but the style is not displayed, and GET https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.js net::ERR_CONNECTION_TIMED_OUTsuch errors appear.
    insert image description here
    insert image description here
    Change the link of css <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">, the style is displayed normally, but jquery and js still report errors, and then change jquery <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>, leaving js Reporting an error, I don’t know what the problem is, there is really no way, let’s just ignore it.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
<!--    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css">-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
</head>
<body>
<div class="ui container">
    <table class="ui celled table" style="margin-top: 40px !important;">
        <thead>
        <tr><th>id</th>
            <th>姓名</th>
            <th>密码</th>
            <th>操作</th>
        </tr></thead>
        <tbody>
        <tr>
            <td data-label="id">James</td>
            <td data-label="name">24</td>
            <td data-label="pwd">Engineer</td>
            <td data-label="edit">
                <a herf="" class="ui button mini green">编辑</a>
                <a herf="" class="ui button mini red">删除</a>
            </td>
        </tr>
        </tbody>
    </table>
</div>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.js"></script>
</body>
</html>

The effect achieved:
insert image description here

  1. Pass a parameter model at the controller layer calling the business layer
    index, which is used to encapsulate the parameters into the model and pass the front-end parameters. A userQuery parameter is also required.
    Then call the service layer userService.listUserByName(userQuery);, and then use "ieda-automatically introduce local variables (introduce local variable)", the shortcut key is ctrl+alt+V, see that it returns one userPageInfo, and then add userPageInfo to the model.
@Controller
public class UserController {
    
    
	@Autowired
	private UserService userService;

	@GetMapping("/")  //用来设置一个地址
	public String index(Model model,UserQuery userQuery){
    
    
		PageInfo<User> userPageInfo = userService.listUserByName(userQuery);
		model.addAttribute("page",userPageInfo);
		return "index";  //定义跳转到index页面
	}
}
  1. The front-end value
    first introduces the thymeleaf template, and then <html>adds the thymeleaf namespace,
<html lang="en" xmlns:th="http://www.thymeleaf.org">

It can be used in html pages. Here we want to display the user information in the database on the page, start <tr>the tag with th, and traverse the array. The variable name of the array is user, which obtains the list collection from the page in a way $. This list collection is our The collection of user objects, and then take the user's id, name, and pwd in <td>the label .$

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
<!--    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.css">-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
</head>
<body>
<div class="ui container">
    <table class="ui celled table" style="margin-top: 40px !important;">
        <thead>
        <tr><th>id</th>
            <th>姓名</th>
            <th>密码</th>
            <th>操作</th>
        </tr></thead>
        <tbody>
        <tr th:each="user:${page.list}">
            <td th:text="${user.id}">James</td>
            <td th:text="${user.name}">24</td>
            <td th:text="${user.pwd}">Engineer</td>
            <td>
                <a herf="" class="ui button mini green">编辑</a>
                <a herf="" class="ui button mini red">删除</a>
            </td>
        </tr>
        </tbody>
    </table>
</div>

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/semantic.min.js"></script>
</body>
</html>

Run the result
insert image description here
and then add a page display part,

<div class="ui attached segment" >
        <table class="m-mobile-wide" width="425px">
            <tbody>
            <tr align="center">
                <td>
                    <a th:href="@{/(pageNum=${page.pageNum}-1)}"  class="ui button basic mini" th:unless="${page.isFirstPage}">上一页</a>
                </td>
                <td><h8 th:text="${page.pageNum}">2</h8>
                    页/共
                    <h8 th:text="${page.pages}">4</h8>
                    页
                    共
                    <h8 th:text="${page.total}">29</h8></td>
                <td>
                    <form name="pageForm" th:action="@{/}" method="get">
                        <div class="ui mini input ">
                            <input type="text" class="m-bg" name="pageNum" placeholder="页码" style="width: 50px!important; height: 27.76px!important;" required>
                            <button type="submit" style="font-size: 11px!important;width: 30px!important; height: 0px!important; border: none;margin: 5px;padding: 0;" class="button mini">
                                跳转
                            </button>
                        </div>
                    </form>
                </td>
                <td> &nbsp;</td>
                <td  style="float: right">
                    <a th:href="@{/(pageNum=${page.pageNum}+1)}" class="ui button basic mini " style="float: right;" th:unless="${page.isLastPage}">下一页</a>
                </td>
            </tr>
            </tbody>
        </table>
    </div>

insert image description here
The paging display of the user list has been realized here.

  1. Query
    the html page according to the user name and add a form to write the search box
<div>
        <form th:action="@{/}" method="post">
        <!--th:action="@{/}"指action走当前的项目路径-->
            <input type="text" name="name" placeholder="输入用户名查找">
            <!--这个name里面一定要与UserQuery的参数名一致,才会把这个值传给name-->
            <input type="submit" value="搜索">
        </form>
    </div>

Next, write @{/}the search method of this jump path:
in the controller:

@PostMapping("/")  //查询表单提交是用post方式
	public String listUserByName(Model model,UserQuery userQuery){
    
    
		PageInfo<User> userPageInfo = userService.listUserByName(userQuery);
		model.addAttribute("page",userPageInfo);
		return "index";
	}

The search function ends.
insert image description here

Guess you like

Origin blog.csdn.net/m0_46538057/article/details/124808532