Springboot+mybatis 搭建并完美整合

来源:互联网 发布:和平网络电视手机安卓 编辑:程序博客网 时间:2024/06/14 15:39

为了减少初学springboot的人少走些弯路,我将我个人觉得最容易操作的方法和最好用的方法介绍给大家。

第一步搭建springboot项目,可以通过建一个maven项目,也可以通过eclipse集成spring suite tool插件。这里通过插件new一个springboot项目。

集成的操作步骤:eclipse --help---Eclipse Maketplace   Search   Find 中输入STS  查找的结果中点击Install安装,有的时候会比较慢。

集成成功后我们来new一个springboot,file -new --找到spring ,点开spring


集成后就会有spring相关选项,选择spring Sarter Project;


点next;







Package  中将com.demo改成com.main,   next;




找到web勾上;生成的项目目录如下,上图中选的springboot的版本不同生成的目录可能不会有点不同。





点开pom.xml文件添加依赖;



  <dependencies>


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

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

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

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

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

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>
        </plugins>
    </build>


将我上面贴出的依赖代码覆盖掉下图中pom.xml中蓝色选中部分.


接下来,更新依赖下载对应的jar:右键项目--maven-update project,


接着添加数据库配置;找到application.properties文件,点开,添加如下配置


spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=xxx
spring.datasource.password=xxxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.port=1111

mybatis.typeAliasesPackage=com.main 
mybatis.mapperLocations=classpath:mapper/*.xml


如果上面的包名没改的应该是com.demo


接着添加一个mapper文件夹,里面放mybaits的SQL文件。目录如下




将你平时用的SQL文件放进去就行了:


userMapper.xml:这里给个样例子:


<?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.demo.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.entity.User">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="cellphone" property="cellphone" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
</resultMap>


<sql id="Base_Column_List">
id,username,password, cellphone, email
</sql>

   <select id="findUserByName" parameterType="HashMap" resultType="com.entity.User">
select 
    <include refid="Base_Column_List" />   
    from user
where username = #{username}
</select>

</mapper>




接着添加controller,dao文件夹,和entity文件夹

注意,注解controller,dao文件夹要放在DemoApplication类(启动)类的相同的包(我的启动类在com.demo包中,刚开始我没改package包名,就是com.demo,你们改成com.main的启动类就在com.main中)或者其子包下才有效,因为springboot的扫描注解的顺序是从启动类的包往下扫描,包括其子包,放在其他包下无效,注解相关的都要如此,切记(想要试错的你可以试试).entity包没有注解不用,位置你们随意放。




文件夹我们建好了,要开始写control类和dao接口了,实体类我就不写了出来了。(SQL语句那个配置文件我上面已经给出个样例子)


mapper接口:


package com.dome.dao;


import java.util.ArrayList;
import java.util.HashMap;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;

import com.entity.User;


@Service
@Mapper
public interface UserMapper {

//本方法无需maper.xml文件
    @Select("select * from user where username = #{username}")
    ArrayList<User> findUser(@Param("username")String username);
       
    //本方法为使用mapper.xml文件的形式
    ArrayList<User> findUserByName(HashMap<String,String>map);
}


这个接口比较牛掰的,可以直接写SQL在上面,也可以用配置文件的形式写,简单的时候我们就不用写配置文件了,方便吧。


controller:代码:

package com.dome.controller;

import java.util.ArrayList;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.dome.dao.UserMapper;
import com.entity.User;



 @RestController
 @RequestMapping({"/home"})
 public class UserController {
     @Autowired
     UserMapper userMapper;


     @RequestMapping(value = "/user")
     @ResponseBody
     public String user(@RequestParam("name") String name){
     
    HashMap<String,String>map= new HashMap<String,String>();
    map.put("username",name);
    ArrayList<User> user = userMapper.findUserByName(map);
         System.out.println("------------------------");
         
         if(user.isEmpty()){
        user=userMapper.findUser("admin");
         }
         return user.isEmpty()?"没有查到任何用户":("查到存在用户名为:"+user.get(0).getUsername()+" 的用户信息");
     }
 }


你们自己添加entity类,和数据库表这些是基本东西后,我们运行项目。

User实体类:

package com.entity;
import java.io.Serializable;
public class User implements Serializable {
/**

*/
private static final long serialVersionUID = 1L;
//ID
private int id;
//密码
private String username;
//用户名
private String password;
//电话号码
private String cellphone;
//邮件
private String email;

public User() {
super();
// TODO Auto-generated constructor stub
}
public User(int id, String username, String password, String cellphone, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.cellphone = cellphone;
this.email = email;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}


右键项目-run as  spring boot app


浏览器输入:http://localhost:1111/home/user?name=test


之前我也老觉得这个spring boot很多坑,还没地方百度,入门很痛苦,所有博主我熬夜将此详细简单的贴出来,希望大家少走弯路











原创粉丝点击