springboot mybatis 连接mysql

1、添加pom依赖

        <!-- Mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
		</dependency>
        <!-- MYSQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2、创建接口Mapper(不是类)和对应的Mapper.xml文件

如果习惯了springmvc的话,那么他就是对应的dao层

UserDao.java
@Mapper
public interface UserDao {
	
	/**
	 * findOne
	 * @param id
	 * @return
	 */
	@Select(value="select *from boot_user where id=#{id}")
	UserInfo findOne(int id);

	/**
	 * findAll
	 * @return
	 */
	List<UserInfo> findAll();
}

UserDao.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.zk.dao.UserDao">

    <!-- findAll -->
    <select id="findAll" resultType="UserInfo">
        select * from boot_user
    </select>
</mapper>

3、实体类

public class UserInfo implements Serializable {
	private static final long serialVersionUID = 6519997700281088880L;
	
	private int id;
	
	private String name;
	
	private String tel;
	
	@JSONField(format="yyyy-MM-dd")
	private Date createTime;
setter getter省略
}

4、修改application.properties 配置文件

#mybatis
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.zk.domain

#DATASOURCE
#初始化数据
spring.datasource.schema=classpath:init-sql/schema.sql
#换链接池,默认是tomcat的连接池
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#高版本mysql需要指定useSSL
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

5、在Controller或Service调用方法测试

    @ResponseBody
    @RequestMapping("/finduser")
    public String findUser() {
        return JSON.toJSONString(userService.findAll());
    }

效果:

131224_WI9j_2942412.png

转载于:https://my.oschina.net/zk875/blog/827764

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值