1. 程式人生 > >springboot+mybatis的簡單的入門例子

springboot+mybatis的簡單的入門例子

1、
本人也是學習springboot不久,其良好的約定簡化了配置,讓我愛不釋手,相比於jfinal,springboot感覺更好一點,當然這是本人意見,不喜勿噴。我在學習中也遇到了各種問題,也查找了各種資料,在這裡就給大家說一下,希望大牛口下留情。
2、
首先新建一個maven專案,我採用的是eclipse,安裝了springsource-tool-suite,如果你電腦沒安裝也不影響,只需要建立相應的目錄就行,如果想安裝可以參考這篇文章http://blog.csdn.net/two_people/article/details/70242206
3、
新建好專案 目錄結構如下
這裡寫圖片描述
當然我的已經是完整的了,你的目錄參照這個,然後我們一步一步的填充
4、


(1)新建實體類,程式碼如下

package com.qbd.model;

import java.io.Serializable;

public class User implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private int uid;
    private String uname;
    private String upassword;
    private int upower;

    public
int getUpower() { return upower; } public void setUpower(int upower) { this.upower = upower; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getUname() { return uname; } public
void setUname(String uname) { this.uname = uname; } public String getUpassword() { return upassword; } public void setUpassword(String upassword) { this.upassword = upassword; } }

(2)新建UserMapper.xml注意:它放在src/main/resources/mapper下程式碼如下

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qbd.dao.UserDao">
    <!-- 定義快取  一般是一級快取,如果用同一個sqlsession 那麼相同查詢直接會從快取中查詢 
    <cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false"></cache>
    -->
    <!-- 查詢所有 -->
    <select id="find" parameterType="Map" resultMap="StudentResult">
        select * from user
        <where>
            <if test="uname!=null and uname!='' ">
                and uname like #{uname}
            </if>
        </where>
        <if test="start!=null and size!=null">
            limit #{start},#{size}
        </if>
    </select>


    <select id="findbyid" parameterType="Integer" resultMap="StudentResult">
        select * from user where uid=#{uid}
    </select>

    <select id="getTotal" parameterType="Map" resultType="Long">
        select count(*) from user
        <where>
            <if test="uname!=null and uname!='' ">
                and uname like #{uname}
            </if>
        </where>
    </select>
    <!-- 按照使用者名稱和密碼查詢 -->
    <select id="getUser" resultMap="StudentResult" parameterType="com.qbd.model.User">
        select *from user where uname=#{uname} and upassword=#{upassword}
    </select>
    <!-- 刪除 -->
    <delete id="delete" parameterType="Integer">
        delete from user where uid=#{uid}
    </delete>
    <!-- 修改 -->
    <update id="update" parameterType="com.qbd.model.User">
        update user
        <set>
            <if test="uname!=null">
                 uname=#{uname},
            </if>
            <if test="upassword!=null">
                upassword=#{upassword},
            </if>
            <if test="upower!=null">
                upower=#{upower},
            </if>
        </set>
        where uid=#{uid}
    </update>
    <!-- 增加 -->
    <insert id="add" parameterType="com.qbd.model.User">
        insert into user values(null,#{uname},#{upassword},#{upower})
    </insert>
    <resultMap type="com.qbd.model.User" id="StudentResult">
        <id property="uid" column="uid"/>
        <result property="uname" column="uname"/>
        <result property="upassword" column="upassword"/>
    </resultMap>
</mapper>

(3)新建UserDao程式碼如下

package com.qbd.dao;

import java.util.List;
import java.util.Map;

import com.qbd.model.User;

public interface UserDao {

    public List<User> getAll();
    public User getUser(User user);
    public int delete(int id);
    public int update(User user);
    public int add(User user);
    public List<User> find(Map<String,Object> map);
    public List<User> findbyid(Integer uid);
    public Long getTotal(Map<String,Object> map);
}

(4)然後分別新建service和serviceimpl,程式碼如下

package com.qbd.service;

import java.util.List;
import java.util.Map;

import com.qbd.model.User;

public interface UserService {

    public List<User> getAll();
    public User getUser(User user);
    public int delete(int id);
    public int update(User user);
    public int add(User user);
    public List<User> find(Map<String,Object> map);
    public Long getTotal(Map<String,Object> map);
}
package com.qbd.serviceimpl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qbd.dao.UserDao;
import com.qbd.model.User;
import com.qbd.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public List<User> getAll() {
        // TODO Auto-generated method stub
        return userDao.getAll();
    }

    public User getUser(User user) {
        // TODO Auto-generated method stub
        return userDao.getUser(user);
    }

    public int delete(int id) {
        // TODO Auto-generated method stub
        return userDao.delete(id);
    }

    public int update(User user) {
        // TODO Auto-generated method stub
        return userDao.update(user);
    }

    public int add(User user) {
        // TODO Auto-generated method stub
        return userDao.add(user);
    }

    public List<User> find(Map<String, Object> map) {
        // TODO Auto-generated method stub
        return userDao.find(map);
    }

    public Long getTotal(Map<String, Object> map) {
        // TODO Auto-generated method stub
        return userDao.getTotal(map);
    }



}

(5)新建controller

package com.qbd.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.qbd.model.User;
import com.qbd.service.UserService;
import com.qbd.utils.PageBean;
import com.qbd.utils.StringUtil;

@Controller
public class UserController {

    private UserService userService;

    public UserService getUserService() {
        return userService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/userlist")
    public Map<String, Object> getAll(String page, String rows, @ModelAttribute User user) throws Exception {
        PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uname", StringUtil.formatLike(user.getUname()));
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        List<User> userList = userService.find(map);
        Long total = userService.getTotal(map);
        map.clear();
        map.put("total", total);
        map.put("users", userList);
        return map;
    }

    @RequestMapping("/list")
    public Map<String, Object> List() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("uname", null);
        map.put("start", null);
        map.put("size", null);
        List<User> userList = userService.find(map);
        Long total = userService.getTotal(map);
        map.clear();
        map.put("total", total);
        map.put("users", userList);
        return map;
    }

    @RequestMapping("/usersave")
    public Map<String, Object> save(@ModelAttribute User user) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        int resultTotal = 0; // �����ļ�¼����
        if (user.getUid() == 0) {
            resultTotal = userService.add(user);
        } else {
            resultTotal = userService.update(user);
        }
        if (resultTotal > 0) {
            map.put("success", "儲存成功");
        } else {
            map.put("success", "儲存失敗");
        }
        return map;
    }

    @RequestMapping("/userdelete")
    public Map<String, Object> delete(@RequestParam(value = "deluids") String ids) throws Exception {
        String[] idsStr = ids.split(",");
        for (int i = 0; i < idsStr.length; i++) {
            userService.delete(Integer.parseInt(idsStr[i]));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", "刪除成功");
        return map;

    }

    @RequestMapping("/index")
    public String index() {

        return "index";
    }
}

(6)完成這些,證明你的基本編碼已經完成,然而並沒有配置,那麼如何採用簡單的springboot的配置那,首先在src/main/resources新建
application.properties內容如下

# 專案contextPath,一般在正式釋出版本中,我們不配置
#server.context-path=/springbootmybatis
# 錯誤頁,指定發生錯誤時,跳轉的URL。請檢視BasicErrorController原始碼便知
server.error.path=/error
# 服務埠
server.port=8888
# session最大超時時間(分鐘),預設為30
server.session.timeout=60
# 該服務繫結IP地址,啟動伺服器時如本機不是該IP地址則丟擲異常啟動失敗,只有特殊需求的情況下才配置
# server.address=192.168.16.11

# tomcat最大執行緒數,預設為200
server.tomcat.max-threads=800
# tomcat的URI編碼
server.tomcat.uri-encoding=UTF-8
# 存放Tomcat的日誌、Dump等檔案的臨時資料夾,預設為系統的tmp資料夾(如:C:\Users\Shanhy\AppData\Local\Temp)
server.tomcat.basedir=D:/log/springboot-tomcat-tmp

#資料庫配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm
spring.datasource.username=root
spring.datasource.password=root

# mybatis_config  
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.qbd.model

# 配置jsp檔案的位置,預設位置為:src/main/webapp
#指向jsp檔案位置:src/main/webapp/pages
spring.mvc.view.prefix: /pages/
spring.mvc.view.suffix: .jsp

(7)然後編寫啟動類來載入這些東西

package com.qbd;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
@MapperScan(basePackages = "com.qbd.dao")//這一步是讓mapper檔案實現dao介面的
public class SpringbootMybatisApplication extends SpringBootServletInitializer {

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringbootMybatisApplication.class);
    }
}