springboot搭建mybatis配置檔案版----連線mysql
阿新 • • 發佈:2019-02-05
一,建立專案
建立一個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;
}
}