插入 200 万行数据可以使用循环来实现,同时为了提高插入效率,可以使用批量插入的方式。

首先,需要创建一个实体类 User 来映射 sys.t__user 表的字段:

public class User {
    private Date createTime;
    private Date updateTime;
    private Long id;
    private String username;
    private String password;
    private String phone;
    private String city;
    private Long roleId;
    private String createUser;
    private String updateUser;
    
    // 省略 getter 和 setter 方法
}

接下来,在 Spring Boot 项目的配置文件 application.properties 中配置数据库连接信息:

spring.datasource.url=jdbc:postgresql://localhost:5432/db_name
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=org.postgresql.Driver

然后,创建一个 UserService 类来处理用户数据的插入操作:

@Service
public class UserService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insertUsers(int count) {
        List<User> userList = generateRandomUsers(count);
        String sql = "INSERT INTO sys.t__user (create_time, update_time, id, username, password, phone, city, role_id, create_user, update_user) VALUES (?,?,?,?,?,?,?,?,?,?)";
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                User user = userList.get(i);
                ps.setTimestamp(1, new Timestamp(user.getCreateTime().getTime()));
                ps.setTimestamp(2, new Timestamp(user.getUpdateTime().getTime()));
                ps.setLong(3, user.getId());
                ps.setString(4, user.getUsername());
                ps.setString(5, user.getPassword());
                ps.setString(6, user.getPhone());
                ps.setString(7, user.getCity());
                ps.setLong(8, user.getRoleId());
                ps.setString(9, user.getCreateUser());
                ps.setString(10, user.getUpdateUser());
            }

            @Override
            public int getBatchSize() {
                return userList.size();
            }
        });
    }

    private List<User> generateRandomUsers(int count) {
        // 生成 count 个随机用户数据
        // 省略具体实现
    }
}

最后,在一个启动类中调用 UserService 的 insertUsers 方法来插入 200 万行数据:

@SpringBootApplication
public class Application implements CommandLineRunner {
    @Autowired
    private UserService userService;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        userService.insertUsers(2000000);
    }
}

以上就是使用 Java 语言、Spring Boot 和 SSM 架构随机插入 200 万行数据到 PostgreSQL 数据库的一个简单实现。请注意根据实际情况修改数据库连接信息和随机生成用户数据的逻辑。

Java Spring Boot 批量插入 PostgreSQL 200 万行数据

原文地址: https://www.cveoy.top/t/topic/o6Eo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录