MyBatis是一款优秀的持久层框架,用于简化JDBC的开发
MyBatis是Apache的一个开源项目iBatis,2010年这个项目由apache迁移到了Google code,并且改名为MyBatis,2013年11月迁移到Github
使用MyBatis查询所有用户信息:
1.准备工作(创建springboot工程、数据库表User、实体类User)
User类
package com.bignyi.pojo;
public class User {
private Integer id;
private String name;
private Short age;
private Short gender;
private String phone;
public User() {
}
public User(Integer id, String name, Short age, Short gender, String phone) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
this.phone = phone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Short getAge() {
return age;
}
public void setAge(Short age) {
this.age = age;
}
public Short getGender() {
return gender;
}
public void setGender(Short gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", gender=" + gender +
", phone='" + phone + '\'' +
'}';
}
}
2.引入MyBatis的相关依赖,配置MyBatis(数据库连接信息)
#?????
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#??????url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#?????????
spring.datasource.username=root
#????????
spring.datasource.password=1234
3.编写SQL语句(注解/XML)
package com.bignyi.mapper;
import com.bignyi.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from User")
public List<User> list();
}
package com.bignyi;
import com.bignyi.mapper.UserMapper;
import com.bignyi.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class SpringbootMybatisQuickstartApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
public void testListUser() {
List<User> userList = userMapper.list();
userList.stream().forEach(user -> System.out.println(user));
}
}
package com.bignyi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootMybatisQuickstartApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisQuickstartApplication.class, args);
}
}
运行结果:
配置SQL提示
默认在mybatis中编写SQL语句是不识别的,可以做如下配置: