1. 程式人生 > >使用spring-boot整合mybaits對資料庫進行操作例項

使用spring-boot整合mybaits對資料庫進行操作例項

新建專案,引入依賴

<parent> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-starter-parent</artifactId> 
       <version>2.0.6.RELEASE</version> 
  </parent>
  
  <dependencies> 
    <dependency> 
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-web</artifactId> 
    </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-data-jpa</artifactId> 
    </dependency> 
	
   <dependency>
    	<groupId>mysql</groupId>
    	<artifactId>mysql-connector-java</artifactId>
   </dependency>
	
    <dependency>
   		<groupId>com.alibaba</groupId>
   		<artifactId>druid-spring-boot-starter</artifactId>
   		<version>1.1.10</version>
	</dependency>
	
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-devtools</artifactId>
		<optional>true</optional>
	</dependency>
	
	<dependency>
    		<groupId>org.mybatis.spring.boot</groupId>
    		<artifactId>mybatis-spring-boot-starter</artifactId>
    		<version>1.3.2</version>
	</dependency>
	<dependency>
        	<groupId>commons-lang</groupId>
       	 	<artifactId>commons-lang</artifactId>
        	<version>2.2</version>
    </dependency>
    <dependency>
    	<groupId>com.github.pagehelper</groupId>
    	<artifactId>pagehelper</artifactId>
    	<version>4.1.6</version>
    </dependency>
  </dependencies>

分頁外掛

import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.pagehelper.PageHelper;

@Configuration
public class PagehelperConfig {
	 @Bean
	 public PageHelper getPageHelper(){
		 PageHelper pageHelper=new PageHelper();
		 Properties properties=new Properties();
		 properties.setProperty("dialect","mysql");
		 properties.setProperty("supportMethodsArguments","true");
		 pageHelper.setProperties(properties);
		 return pageHelper;
	 }
}

控制層

@RestController
public class UserController {

    @Autowired
    private UserService userService;
	@GetMapping(value = "users")
	public Result listUser(User user, String page, String limit){
		try {
			Result pb=userService.queryUser(user, page, limit);
			return pb;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	@PostMapping(value = "user")
	public Result addUser(User user){
		Result result=new Result();
		try {
			userService.addUser(user);
		}catch (Exception e){
			result.setCode(1);
			result.setMsg("新增出錯"+e.getMessage());
		}
		return result;
	}

	@DeleteMapping(value = "user/{id}")
	public Result deleteUser(@PathVariable int id){
		Result result=new Result();
			try {
				userService.deleteUser(id);
			}catch (Exception e){
				result.setCode(1);
				result.setMsg("刪除失敗"+e.getMessage());
			}
		return result;
	}
	
	@PutMapping(value = "user/{id}")
	public Result updateUser(@PathVariable int id,User user){
		Result result=new Result();
		user.setId(id);
		try {
			userService.updateUser(user);
		}catch (Exception e){
			result.setCode(1);
			result.setMsg("修改失敗"+e.getMessage());
		}
		return result;
	}
}

service層

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	public Result queryUser(User user,String curPage, String numPage) throws SQLException {
		//第一次訪問沒有當前頁
		if(StringUtils.isEmpty(curPage)) {
			curPage="1";
		}
		if(StringUtils.isEmpty(numPage)) {
			numPage="10";
		}
		//轉換成int型別
		int cur=Integer.parseInt(curPage);
		int num=Integer.parseInt(numPage);
		List<User> queryUser=userMapper.queryUser(user, cur, num);
		PageInfo<User> pi=new PageInfo<User>(queryUser);
		Result result=new Result();
		result.setCode(0);
		result.setCount((int)pi.getTotal());
		result.setData(queryUser);
		return result;
	}
	public void addUser(User user) {
		userMapper.addUser(user);
	}

	public void deleteUser(int id) {
		userMapper.deleteUser(id);
	}

	public void updateUser(User user) {
		userMapper.updateUser(user);
	}
}

service介面

public interface UserService {
	public Result queryUser(User user, String curPage, String numPage) throws SQLException;

	public void addUser(User user);

	public void deleteUser(int id);

	public void updateUser(User user);
}

實體類

public class User {
    private int id;
    private String userName;
    private String userSex;
    private String userAge;
    private String userPhone;
    private String userMoney;
    private String userEmail;
    
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserSex() {
		return userSex;
	}
	public void setUserSex(String userSex) {
		this.userSex = userSex;
	}
	public String getUserAge() {
		return userAge;
	}
	public void setUserAge(String userAge) {
		this.userAge = userAge;
	}
	public String getUserPhone() {
		return userPhone;
	}
	public void setUserPhone(String userPhone) {
		this.userPhone = userPhone;
	}
	public String getUserMoney() {
		return userMoney;
	}
	public void setUserMoney(String userMoney) {
		this.userMoney = userMoney;
	}
	public String getUserEmail() {
		return userEmail;
	}
	public void setUserEmail(String userEmail) {
		this.userEmail = userEmail;
	}
}
public class Result {
    private int code;
    private String msg;
    private int count;
    private List data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public List getData() {
        return data;
    }

    public void setData(List data) {
        this.data = data;
    }
}

sql對映類

@Mapper
public interface UserMapper {
	
		@SelectProvider(type=query.class,method="getQuery")
		public List<User> queryUser(@Param("u") User user,@Param("pageNum") int pageNum,@Param("pageSize") int pageSize);	
	
		@Insert("insert into user(username,usersex,userage,userphone,usermoney,useremail) values(#{userName},#{userSex},#{userAge},#{userPhone},#{userMoney},#{userEmail})")
		public void addUser(User user);
		
		@Delete("delete from user where id=#{0}")
		public void deleteUser(int id);
		
		@Update("update user set username=#{userName},usersex=#{userSex},userage=#{userAge},userphone=#{userPhone},usermoney=#{userMoney},useremail=#{userEmail} where id=#{id}")
		public void updateUser(User user);
		
		static class query{
			public String getQuery(Map<String,User> map) {
				User users=map.get("u");
				SQL sql=new SQL();
				sql.SELECT("*");
				sql.FROM("user");
				if(StringUtil.isEmpty(users.getUserName()) && StringUtil.isEmpty(users.getUserMoney())) {		
					users.setUserName("");
					sql.WHERE(" username like '%'");
					return sql.toString();
				}else if(!StringUtil.isEmpty(users.getUserName()) &&StringUtil.isEmpty(users.getUserMoney())){
					users.setUserName("%"+users.getUserName()+"%");
					sql.WHERE(" username like #{u.userName}");
					return sql.toString();
				}else if(StringUtil.isEmpty(users.getUserName()) && !StringUtil.isEmpty(users.getUserMoney())) {
					sql.WHERE(" usermoney = #{u.userMoney}");
					return sql.toString();
				}else {
					users.setUserName("%"+users.getUserName()+"%");
					sql.WHERE(" username like #{u.userName}");
					sql.AND();
					sql.WHERE(" usermoney = #{u.userMoney}");
					return sql.toString();
				}
			}
		}
}

resources配置檔案:application.yml

server.port=8081
spring.redis.host=192.168.0.192
spring.redis.password=123456789
spring.datasource.url=jdbc:mysql://localhost/my_mysql
spring.datasource.username=tan_tan
spring.datasource.password=789456123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.stat-view-servlet.login-username=tantan
spring.datasource.druid.stat-view-servlet.login-password=123456

main方法:啟動專案

@RestController
@SpringBootApplication
public class Example {

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

webapp下新建resource匯入layui
webapp下匯入jquery

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品列表</title>
    <link rel="stylesheet" href="resource/layui/css/layui.css"/>
    <script src="resource/layui/layui.js"></script>
    <script type="text/javascript" src="jquery-3.3.1.js"></script>
    <script type="text/javascript">
        layui.use('form',function () {
            var form=layui.form;
            form.on('submit(myForm)', function(data){
                layui.table.reload('userTable', {
                    url: 'users'
                    ,where: data.field //設定非同步資料介面的額外引數
                    ,page: {
                        curr: 1 //重新從第 1 頁開始
                    }
                });
                return false;
            });
            form.on('submit(addForm)', function(data){
       
                $.ajax({
                    url:'user',
                    dataType:'json',
                    data:data.field,
                    type:'post',
                    success:function (d) {
                        if(d.code==0){
                            alert("增加成功");
                            layer.close(addWindow);
                            layui.table.reload('userTable', {
                                url: 'users'
                            });
                            $("#addForm input[class=layui-input]").val("");
                        }else{
                           console.log(d.msg);
                        }
                    },
                })
                return false;
            });
            form.on('submit(updateForm)', function(data){
                data.field["_method"]="put";
                $.ajax({
                    url:'user/'+data.field.id,
                    dataType:'json',
                    data:data.field,
                    type:'post',
                    success:function (d) {
                        if(d.code==0){
                            alert("修改成功");
                            layer.close(updateWindow);
                            layui.table.reload('userTable', {
                                url: 'users',
                            });
                        }else{
                            console.log(d.msg);
                        }
                    }
                })
                return false;
            });
        });
        layui.use('table', function(){
            var table = layui.table;

            table.render({
                elem: '#userTable'
                ,height: 474
                ,width: 984
                ,url: 'users' //資料介面
                ,page: true //開啟分頁
                ,cols: [[ //表頭
                    {field: 'id', title: '使用者編號', width:120, sort: true, fixed: 'left'}
                    ,{field: 'userName', title: '使用者姓名', width:120}
                    ,{field: 'userSex', title: '使用者性別', width:120, sort: true}
                    ,{field: 'userAge', title: '使用者年齡', width:120}
                    ,{field: 'userPhone', title: '使用者電話', width: 120}
                    ,{field: 'userMoney', title: '使用者金額', width: 120, sort: true}
                    ,{field: 'userEmail', title: '使用者郵箱', width: 120, sort: true}
                    ,{field: 'caoZuo', title: '操作', width: 120, sort: true,templet: function(d){
                            var str=JSON.stringify(d);
                            return "<button onclick='userDelete("+d.id+")'>刪除</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                                    "<button onclick=\"userUpdate()\" data='"+str+"'>修改</button>";
                        }}
                    
                ]]
            });
        });
        var addWindow=null;
        function addUser() {
            layui.use('layer', function(){
                addWindow=layer.open({
                    type: 1,
                    area: ['500px', '410px'],
                    content:$("#addForm")
                });
            });

        };
        function userDelete(id) {
            $.ajax({
                url: 'user/'+id,
                dataType: 'json',
                data:{
                    "_method":"delete"
                },
                type: 'post',
                success: function (d) {
                    if (d.code == 0) {
                        alert("刪除成功");
                        layui.table.reload('commodityTable', {
                            url: 'users',
                            page:1
                        });

                    } else {s
                        console.log(d.msg);
                    }
                }
            })
            return false;
        }
        var updateWindow=null;
        function userUpdate(str) {
            var source=JSON.parse(event.srcElement.getAttribute("data"));
            layui.use('layer', function(){
                updateWindow=layer.open({
                    type: 1,
                    area: ['500px', '410px'],
                    content:$("#updateForm")
                })
            });
            layui.form.val("updateForm",source)
        }
    </script>
</head>
<body>
<form class="layui-form" action="">
    <div class="layui-inline">
        <label class="layui-form-label">使用者姓名</label>
        <div class="layui-input-inline" style="width: 200px;">
            <input type="text" name="userName" placeholder="請輸入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-inline">
        <label class="layui-form-label">使用者金額</label>
        <div class="layui-input-inline" style="width: 200px;">
            <input type="text" name="userMoney" placeholder="請輸入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-inline">
        <div class="layui-input-inline" style="width: 100px;">
            <button class="layui-btn" lay-submit lay-filter="myForm">查詢</button>
        </div>
    </div>
    <div class="layui-inline">
        <div class="layui-input-inline" style="width: 100px;">
            <a href="javascript:addUser()" class="layui-btn">新增</a>
        </div>
    </div>
</form>

<table id="userTable"></table>
</body>
</html>

<!--新增-->
<form id="addForm" class="layui-form" style="display: none"> <!-- 提示:如果你不想用form,你可以換成div等任何一個普通元素 -->
    <div class="layui-form-item">
        <label class="layui-form-label">使用者姓名</label>
        <div class="layui-input-block">
            <input type="text" name="userName" lay-verify="required" placeholder="請輸入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者性別</label>
        <div class="layui-input-block">
            <input type="text" name="userSex" lay-verify="required" placeholder="請輸入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者年齡</label>
        <div class="layui-input-block">
            <input type="text" name="userAge" lay-verify="number" placeholder="請輸入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者電話</label>
        <div class="layui-input-block">
            <input type="text" name="userPhone" lay-verify="phone" placeholder="請輸入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者金額</label>
        <div class="layui-input-block">
            <input type="text" name="userMoney" lay-verify="number" placeholder="請輸入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者郵箱</label>
        <div class="layui-input-block">
            <input type="text" name="userEmail" lay-verify="email" placeholder="請輸入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="addForm">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!--修改-->
<form id="updateForm" class="layui-form" lay-filter="updateForm" style="display: none"> <!-- 提示:如果你不想用form,你可以換成div等任何一個普通元素 -->
    <input type="hidden" name="id">
    <div class="layui-form-item">
        <label class="layui-form-label">使用者姓名</label>
        <div class="layui-input-block">
            <input type="text" name="productName" lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者性別</label>
        <div class="layui-input-block">
            <input type="text" name="userSex" lay-verify="required" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者年齡</label>
        <div class="layui-input-block">
            <input type="text" name="userAge" lay-verify="number" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者電話</label>
        <div class="layui-input-block">
            <input type="text" name="userPhone" lay-verify="phone" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者金額</label>
        <div class="layui-input-block">
            <input type="text" name="userMoney" lay-verify="number" placeholder="請輸入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">使用者郵箱</label>
        <div class="layui-input-block">
            <input type="text" name="userEmail" lay-verify="email" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="updateForm">立即儲存</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>


<!--<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>-->