- 搭建SpringBoot工程
- 引入mybatis起步依赖,添加mysq驱动
你所要连接的数据库驱动和Mybatis Framework
3. 编写DataSource和MyBatis相关配置
# datasource
spring:
datasource:
# serverTimezone=UTC 时区
url: jdbc:mysql:///你的数据库?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 密码
#mybatis
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml #mapper映射注册
- 定义表和实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String unmae;
private String upassword;
}
- 编写dao和mapper文件/纯注解开发
在启动类加载扫描接口的路径
@SpringBootApplication
@MapperScan("com.lzk.mapper")//在启动类加载扫描接口的路径
public class Springbootdemo2Application {
public static void main(String[] args) {
SpringApplication.run(Springbootdemo2Application.class, args);
}
}
//userMapper接口
@Repository //作用不只是将类识别为Bean,同时它还能将所标注的类中抛出的数据访问异常封装为 Spring 的数据访问异常类型
@Mapper
public interface userMapper {
//配置
List<User> findAll();
//注解
@Select("select * from users where id=1")
User finaById();
}
<!--userMapper.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">
<!--报错“Type interface lzk.dao.userMapper is not known to the MapperRegistry” 原因: 路径间隔是.-->
<mapper namespace="com.lzk.mapper.userMapper">
<!--id:给该sql映射一个代号 resultType:返回的值的数据类型-->
<select id="findAll" resultType="com.lzk.pojo.User">
select * from users
</select>
</mapper>
- 测试
@RunWith(SpringRunner.class)
@SpringBootTest
class Springbootdemo2ApplicationTests {
@Autowired
private userMapper userMapper;
@Test
public void test1(){
List<User>userList=userMapper.findAll();
for (User user : userList) {
System.out.println(user);
}
System.out.println("--------------------------");
User user=userMapper.finaById();
System.out.println(user);
}
}