发表于: 2021-11-03 22:54:42
1 905
maven mybatis 批量插入数据库
创建新项目task
项目目录结构
项目需要倒入的包,编辑pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>task</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.ow2.util.bundles</groupId>
<artifactId>slf4j-1.6.1</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.0-alpha0</version>
</dependency>
</dependencies>
</project>
配置数据库链接 SqlMapConfig.xml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration >
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 和Spring整合后envirnmentss 配置将被移除-->
<environments default="mysql">
<environment id="mysql">
<!-- 使用jdbc事务管理-->
<transactionManager type="JDBC"/>
<!-- 数据库连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/task"/>
<property name="username" value="root"/>
<property name="password" value="deng796443"/>
</dataSource>
</environment>
</environments>
<!-- 写完SQL映射文件后为了能让mybatis资源文件加载类解析Mapper文件-->
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
User实体类定义:
package com.jnshu;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable{
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
Dao层接口定义:
package com.jnshu.Dao;
import com.jnshu.User;
import java.util.List;
/*
* 用户的持久层接口*/
public interface IUserDao {
List<User> findAll();
void insertBatch(List<User> users);
}
sql写法:
<?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.jnshu.Dao.IUserDao">
<!--配置查询所有,需要指定map映射的结果集-->
<select id="findAll" resultType="com.jnshu.User">
select * from user;
</select>
<insert id="insertBatch" parameterType="com.jnshu.User">
insert into user (username,birthday,sex,address) values
<foreach collection="list" item="user" separator="," close=";">
(#{user.username}, #{user.birthday}, #{user.sex}, #{user.address})
</foreach>
</insert>
</mapper>
测试类
import com.jnshu.Dao.IUserDao;
import com.jnshu.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.mybatis.spring.SqlSessionTemplate;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MybatisTest {
private SqlSession sqlSession;
private IUserDao dao;
private InputStream is;
private SqlSessionTemplate sqlTemplate;
@BeforeAll
public void init() throws IOException{
//1)读取配置文件
is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2)创建SqlSessionFactory
SqlSessionFactoryBuilder sqlBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlFactory = sqlBuilder.build(is);
//3)使用工厂创建SqlSession对象
sqlSession = sqlFactory.openSession();
//4)使用SqlSession创建Dao接口的代理对象
dao = sqlSession.getMapper(IUserDao.class);
}
@Test
public void testFindAll() {
//5)使用代理对象执行方法
List<User> users = this.dao.findAll();
for (User user : users) {
System.out.println(user);
}
}
@Test
public void testBatchInsert() {
List<User> users = new ArrayList<User>();
int userCount = 100;
User user = new User();
for (int i = 0; i != userCount; i++) {
user.setUsername("王林");
user.setSex("男");
user.setAddress("深圳");
Date date = new Date();
date.setTime(100L);
user.setBirthday(date);
users.add(user);
}
dao.insertBatch(users);
}
@AfterAll
public void close() throws IOException{
//这里需要提交事务
sqlSession.commit();
//6)释放资源
sqlSession.close();
is.close();
}
}
运行结果
总结:在写程序中一定要仔细,在创建过程中出现无数问题,写完代码后一运行一堆问题
比如刚开始的时候找不到Sqlmapconfig.xml文件
就这个问题找问题找了一个上午
然后就是DAO层结构定义前面一直不怎么理解,导致的报错信息
Type interface com.jnshu.Dao.IUserDao is not known to the MapperRegistry.
找到了问题所在是DAO层接口与mapper 中namespace 不一致导致的
<mapper namespace="com.jnshu.Dao.IUserDao">
然后就是运行又报错!!!!
org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: java.sql.SQLSyntaxErrorException: Unknown column 'sex' in 'field list'
### The error may exist in UserMapper.xml
自己前面粗心忘记了用的是自己之前写的SqlMapCondigxml
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
数据库忘记已经重新换了,更改数据名后正常运行。
写这个批量插入学会了写测试,找问题,链接数据库的问题以及对maven 的理解更好了,软件使用程度上升了
评论