标签:数据库 findall 测试 mapper pat header ntb timezone 连接
这里采用的是IDEA演示,生成后的目录是这样的:
关于项目结构这里要注意的是:所有包必须于springboot启动类处于同一包下或者都位于springboot的子包下,这样springboot才会扫描到容器里的各个组件!
编写实体类user:
public class User {
private Long id;//编号
private String username;//用户名
private String password;//密码
@Override
public String toString() {
return "User{" +
"id=" + id +
", username=‘" + username + ‘\‘‘ +
", password=‘" + password + ‘\‘‘ +
‘}‘;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
熟悉mybatis的应该知道面向接口编程,所以创建一个mapper包放主要方法与UserMapper.xml对应
UserMapper:
@Mapper
public interface UserMapper {
List<User> findAll();
}
@Mapper注解目的就是为了不再写mapper映射文件,从mybatis3.4.0开始加入了@Mapper注解。指定该接口是用来操作数据库的,但是实际开发中注解少用,更多的还是使用xml配置文件。
编写service层userservice:
public interface UserService {
List<User> findAll();
}
实现该服务userserviceImp:
@Service("userService")
public class UserServiceImp implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
}
接下来在application.yml中配置数据源:
server:
port: 8080
spring:
#数据库连接配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: xhj970829
#mybatis的相关配置
mybatis:
#mapper配置文件
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.sprintboot_mybatis.entity
#开启驼峰命名
configuration:
map-underscore-to-camel-case: true
编写一个controller测试一下:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
public List<User> findAll(){
return userService.findAll();
}
}
运行并访问localhost:8080/user/findAll
标签:数据库 findall 测试 mapper pat header ntb timezone 连接
原文地址:https://www.cnblogs.com/xhj928675426/p/13154181.html