概述
一,创建项目
创建一个springboot项目,使用Gradle依赖,添加的依赖为:
compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2')
runtime('mysql:mysql-connector-java')
// https://mvnrepository.com/artifact/com.alibaba/druid
compile group: 'com.alibaba', name: 'druid', version: '1.1.9'
二,配置文件
yml:
server:
port: 8080
mybatis:
mapper-locations: classpath:/mybatis/mapper/*.xml
config-location: classpath:/mybatis/mybatis-config.xml
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_mybatis
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
</typeAliases>
</configuration>
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.meng.IDAO.UserDao" >
<resultMap id="UserMap" type="com.meng.entity.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="username" property="username" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
<result column="ctm" property="ctm" jdbcType="TIMESTAMP"/>
</resultMap>
<select id="getByPrimaryKey" parameterType="java.lang.Integer" resultMap="UserMap" >
SELECT *
FROM tb_user
WHERE id = #{id}
</select>
</mapper>
三,数据库设计
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`username` varchar(50) NOT NULL COMMENT '用户名',
`age` int(11) NOT NULL COMMENT '年龄',
`ctm` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
四,代码书写
entity:
需要生成getter和setter方法,无参构造器和有参构造器,也可以生成toString方法
import java.util.Date;
private int id;
private String username;
private int age;
private Date ctm;
dao:
通过id来查询用户信息,需加注解@Mapper
@Mapper
public interface UserDao {
User getByPrimaryKey(@Param("id")Integer id);
}
service:
要点:1.类上面要加@Service
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.meng.entity.User;
import com.meng.mapper.UserMapper;
@Service
public class UserService{
@Resource
private UserMapper userMapper;
public User getByPrimaryKey(Integer id) {
return userMapper.getUserById(id);
}
}
controller:
采用Rest风格返回json数据
@RestController
public class UserController {
@Autowired
private UserService uService;
@RequestMapping("/getUser")
public User getUser() {
User u = uService.getUserById(1);
return u;
}
}
五,成功效果
最后
以上就是幸福时光为你收集整理的springboot搭建mybatis配置文件版----连接mysql的全部内容,希望文章能够帮你解决springboot搭建mybatis配置文件版----连接mysql所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复