SpringBoot学习3.3-MyBatis简单例子

目录

1.mysql数据库环境的搭建(建库、建表)

2.maven坐标

3.建表t_user对应的实体类

4.数据库操作接口mapper

 5.对mapper的扫描策略-@MapperScan注解

6.调用mapper接口操作数据库


1.mysql数据库环境的搭建(建库、建表)

参考:SpringBoot学习3.0-访问mysql

数据库增加mybatis的配置,配置日志级别:

#--------------mybatis配置  start --------------#
logging.level.root=DEBUG
logging.level.org.springframework=DEBUG
logging.level.org.org.mybatis=DEBUG
#--------------mybatis配置  end --------------#

2.maven坐标

<!-- 连接数据库依赖  -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!-- mysql依赖  -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>

<!-- mybatis依赖  -->
<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.0</version>
</dependency>

mybatis-spring-boot-starter引入mybatis依赖。

3.建表t_user对应的实体类

public class UserDto {

	private int id;

	private String name;

	private int sex;

	private String note;

        // setters and getters

	@Override
	public String toString() {
		return "id=" + id + ",name=" + name + ",sex=" + sex + ",note=" + note;
	}
}

4.数据库操作接口mapper

@Repository // 扫描到IoC
public interface UserMapper {
	UserDto getUserById(int id);
}

注解@Repository是必须的,否则无法装配到IoC。  

<?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.zyf.springDb.mybatis.dao.UserMapper">
    <select id="getUserById" parameterType="int" resultType="com.zyf.springDb.mybatis.dto.UserDto">
        select id, name, sex, note from t_user where id = #{id}
    </select>
</mapper>

 5.对mapper的扫描策略-@MapperScan注解

// mybatis扫描策略:basePackages=基础包,annotationClass = 注解名
@MapperScan(basePackages = "com.zyf.springDb.mybatis.*", annotationClass = Repository.class)
@SpringBootApplication
public class SpringDbApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringDbApplication.class, args);
	}

}

扫描策略@MapperScan是必须的,否则无法装配到IoC。 

6.调用mapper接口操作数据库

@Service
public class UserMyBatisService {

	@Autowired
	private UserMapper userMapper;
	
	public UserDto getUserById(int id){
		return userMapper.getUserById(id);
	}
}

 

github:https://github.com/zhangyangfei/SpringBootLearn  其中的springDb工程。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值