sping6,mybatis3.5.10,maven 3.6.1
若引入失败可以手动下载好jar包粘贴到本地maven仓库的对应位置
org.springframework
spring-context
6.0.0-M2
org.springframework
spring-jdbc
6.0.0-M2
mysql
mysql-connector-java
8.0.31
org.mybatis
mybatis
3.5.10
org.mybatis
mybatis-spring
2.0.7
com.alibaba
druid
1.2.13
junit
junit
4.13.2
test
再引入 spring6 的仓库
repository.spring.milestone
Spring Milestone Repository
https://repo.spring.io/milestone
为这张表准备一个 Pojo 类,并用注解的方式将其纳入 spring 容器进行管理
package mybatis.Pojo;
import org.springframework.stereotype.Component;
@Component
public class BirthBean {
private String name;
private int age;
private String birthday;
public BirthBean() {
}
public BirthBean(String name, int age, String birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "BirthBean{" +
"name='" + name + '\'' +
", age=" + age +
", birthday='" + birthday + '\'' +
'}';
}
}
持久层:数据库表的 Mapper 接口
public interface BirthdayMapper {
@Select("select * from t_birthday")
@Results({
@Result(property = "name",column = "name"),
@Result(property = "age",column = "age"),
@Result(property = "birthday",column = "birthday")
})
List selectAll();
int insert(BirthBean birthBean);//插入字段
List selectAge();//查找年龄大于 10 的记录
}
业务层:数据库表的 Service 接口
public interface BirthService {
//批量插入用户逻辑
public void insertGroup(List lists);
}
数据库表的 Service 实现类
public class BirthServiceImpl implements BirthService {
@Autowired
BirthdayMapper birthdayMapper;//从容器中拿到 BirthdayJMapper
/**
* 批量添加用户
*/
@Override
public void insertGroup(List lists) {
for(BirthBean birthBean : lists){
birthdayMapper.insert(birthBean);
}
}
}
Mapper 接口对应的 xml 文件
insert into t_birthday values(#{name},#{age},#{birthday})
spring.xml
mybatis 核心配置文件
数据库配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/learnbase
jdbc.username=root
jdbc.password=1234
@Test
public void insertGroupText(){
BirthServiceImpl bsi = new BirthServiceImpl();
List lists = new ArrayList<>();
lists.add(new BirthBean("序列001",1,"?-?-?"));
lists.add(new BirthBean("序列002",2,"?-?-?"));
bsi.insertGroup(lists);
List ans = bsi.selectAll();
System.out.println(ans);
}
若查询到的数据库表中多了两个字段,则代表添加成功
报错找不对对应的 Bean 多半是依赖注入的问题,检查 @Autowired 是非成功拿到了容器中的类