SpringBoot ------ Web开发(二)整合Mybatis

**

SpringBoot整合Mybatis

**

Step1:pom导入

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<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>
		<!-- mybaties -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.1.1</version>
		</dependency>
		<!-- mysql驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency> 
			<groupId>org.springframework.boot</groupId> 
			<artifactId>spring-boot-starter-web</artifactId> 
		</dependency>
	</dependencies>

Step2:数据库配置文件

1、Mapper.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.ykd.mapper.UserMapper" >

    <insert id="save">
        insert into user (username,password) VALUES(#{0},#{1})
    </insert>
    <select id="findByUsername" resultType="com.ykd.model.User" parameterType="string">
        select * from user where username = #{username,jdbcType=VARCHAR}
    </select>
</mapper>

注意这里需要在pom中添加下面代码

<build>
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.xml</include>
      </includes>
    </resource>
  </resources>
</build>

step3:Controller

@RestController  //声明Rest风格的控制器
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 通过姓名查找用户信息
     * @param name
     * @return
     */
    @RequestMapping("find")
    @ResponseBody    //响应体,自动返回json格式数据
    public User find(String name){
        return userService.findByName(name);
    }

    /**
     * 创建一个新的用户
     * @param name
     */
    @ResponseBody
    @RequestMapping("/add")
    public int add(String name) {
        return userService.insert(name,"123");
    }
}

Step4:App

@EnableAutoConfiguration
@ComponentScan(basePackages = "com.ykd")  		//扫描controller层和servce层
@MapperScan(value="com.ykd.mapper")				//扫描mapper层
public class App
{
    public static void main(String[] args) {
        //启动springboot项目
        SpringApplication.run(App.class,args);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值