章节小结增加筛选条件

教师端学生端增加批量增加账号
dev_202412
rong.liu 3 months ago
parent 5fa033bc9e
commit e52c8584e4
  1. 4
      occupationlab/src/main/java/com/huoran/occupationlab/controller/CourseChapterController.java
  2. 2
      occupationlab/src/main/java/com/huoran/occupationlab/service/CourseChapterService.java
  3. 6
      occupationlab/src/main/java/com/huoran/occupationlab/service/impl/CourseChapterServiceImpl.java
  4. 42
      users/src/main/java/com/huoran/users/controller/AddUsersInBatchesController.java
  5. 40
      users/src/main/java/com/huoran/users/entity/req/AddUsersInBatchesReq.java
  6. 4
      users/src/main/java/com/huoran/users/mapper/HrUserAccountMapper.java
  7. 2
      users/src/main/java/com/huoran/users/mapper/HrUserInfoMapper.java
  8. 8
      users/src/main/java/com/huoran/users/mapper/StudentMapper.java
  9. 18
      users/src/main/java/com/huoran/users/mapper/xml/HrUserAccountMapper.xml
  10. 7
      users/src/main/java/com/huoran/users/mapper/xml/HrUserInfoMapper.xml
  11. 17
      users/src/main/java/com/huoran/users/mapper/xml/StudentMapper.xml
  12. 5
      users/src/main/java/com/huoran/users/service/IHrUserInfoService.java
  13. 144
      users/src/main/java/com/huoran/users/service/impl/HrUserInfoServiceImpl.java
  14. 155
      users/src/main/java/com/huoran/users/utils/UserGenerator.java
  15. 171
      users/src/main/java/com/huoran/users/utils/UserGenerator1.java

@ -34,8 +34,10 @@ public class CourseChapterController {
@GetMapping("/queryChaptersAndSubsections/{courseId}")
public R queryChaptersAndSubsections(
@ApiParam(name = "courseId", value = "课程ID", required = true)
@PathVariable String keyword,
@ApiParam(name = "keyword", value = "关键词", required = false)
@PathVariable String courseId) {
List<ChapterVO> chapterList = courseChapterService.getChapterTree(courseId);
List<ChapterVO> chapterList = courseChapterService.getChapterTree(courseId,keyword);
return R.ok().put("chapterList", chapterList);
}

@ -14,7 +14,7 @@ import java.util.List;
*/
public interface CourseChapterService extends IService<CourseChapter> {
List<ChapterVO> getChapterTree(String courseId);
List<ChapterVO> getChapterTree(String courseId, String keyword);
boolean removeChapter(String chapterId);

@ -1,6 +1,5 @@
package com.huoran.occupationlab.service.impl;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@ -36,9 +35,12 @@ public class CourseChapterServiceImpl extends ServiceImpl<CourseChapterMapper, C
private CourseSubsectionMapper courseSubsectionMapper;
@Override
public List<ChapterVO> getChapterTree(String courseId) {
public List<ChapterVO> getChapterTree(String courseId, String keyword) {
// 根据课程ID查询所有章节
QueryWrapper<CourseChapter> chapterWrapper = new QueryWrapper<>();
if (!StringUtils.isEmpty(keyword)){
chapterWrapper.like("name", keyword);
}
chapterWrapper.eq("course_id", courseId);
//降序查询
chapterWrapper.orderByAsc("sort");

@ -0,0 +1,42 @@
package com.huoran.users.controller;
import com.huoran.common.response.R;
import com.huoran.common.utils.TokenUtils;
import com.huoran.users.entity.req.AddUsersInBatchesReq;
import com.huoran.users.service.IHrUserAccountService;
import com.huoran.users.service.IHrUserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
//@Api(tags = "批量新增用户", tags = "批量新增用户")
@Api(value = "批量新增用户相关", tags = "批量新增用户相关")
@RequestMapping("/users/batchProcessing")
@RestController
public class AddUsersInBatchesController {
@Autowired
private IHrUserInfoService userService;
@Autowired
private IHrUserAccountService userAccountService;
@ApiOperation(value = "生成用户")
@PostMapping("/users/generate")
public R generateUsers(@RequestBody AddUsersInBatchesReq addUsersInBatchesReq) {
Integer school_id = TokenUtils.getSchoolId();
addUsersInBatchesReq.setSchoolId(school_id);
userService.generateUsersWithParams(addUsersInBatchesReq);
return R.ok("用户生成成功");
}
//校验姓名/学号工号是否存在
@ApiOperation(value = "校验姓名/学号工号是否存在")
@PostMapping("/checkUserNameOrWorkNumber")
public R checkUserNameOrWorkNumber(){
return userService.checkUserNameOrWorkNumber(TokenUtils.getAccountId());
}
}

@ -0,0 +1,40 @@
package com.huoran.users.entity.req;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class AddUsersInBatchesReq {
@ApiModelProperty(value = "生成用户数量")
private Integer numberOfUsers;
@ApiModelProperty(value = "批量生成数量")
private Integer batchSize;
@ApiModelProperty(value = "平台id")
private String platformId;
@ApiModelProperty(value = "学校id", hidden = true)
private Integer schoolId;
@ApiModelProperty("平台端id区分:0->教师端 1->学生端")
private Integer type;
@ApiModelProperty("班级id")
private Integer classId;
//一级部门
@ApiModelProperty("员工架构ID/一级部门id")
private Integer staffArchitectureId;
//二级部门
@ApiModelProperty("二级部门ID")
private Integer gradeId;
@ApiModelProperty(value = "角色id")
private String roleId;
}

@ -80,4 +80,8 @@ public interface HrUserAccountMapper extends BaseMapper<HrUserAccount> {
HrUserAccount selectAccount(@Param("platform")String platform,@Param("account") String account, @Param("password") String password);
HrUserAccount getOne(String openid);
void batchInsert(@Param("list") List<HrUserAccount> batchAccounts);
boolean existsByAccount(@Param("account") String account);
}

@ -55,4 +55,6 @@ public interface HrUserInfoMapper extends BaseMapper<HrUserInfo> {
ProfileDetailsRes personalFile(Integer userId);
void updateStudentAffiliatedInstitutionId(@Param("competitionId")Integer competitionId,@Param("accountId") Integer id, @Param("teamId")Integer teamId, @Param("studentAffiliatedInstitutionId")Integer studentAffiliatedInstitutionId);
void batchInsert(@Param("list")List<HrUserInfo> batchUsers);
}

@ -1,9 +1,14 @@
package com.huoran.users.mapper;
import com.huoran.common.entity.HrUserAccount;
import com.huoran.users.entity.Student;
import com.huoran.users.entity.req.AddUsersInBatchesReq;
import org.apache.ibatis.annotations.Mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* @描述学生表 Mapper 接口
@ -13,4 +18,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
void batchInsert(@Param("list") List<HrUserAccount> batchAccounts,@Param("classId") Integer classId);
void batchInsertTeachers(@Param("list")List<HrUserAccount> batchAccounts,@Param("req") AddUsersInBatchesReq req);
}

@ -24,6 +24,14 @@
INSERT INTO occupationlab.ol_student(`account_id`, `class_id`, `school_id`, `create_time`, `update_time`)
VALUES (#{accountId}, #{classId}, #{schoolId}, now(), now());
</insert>
<insert id="batchInsert" useGeneratedKeys="true" keyProperty="id">
INSERT INTO hr_user_account (user_id, password, role_id, is_enable, create_time, account, platform_id,type,school_id)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.userId}, #{item.password}, #{item.roleId}, #{item.isEnable}, #{item.createTime}, #{item.account},
#{item.platformId},#{item.type},#{item.schoolId})
</foreach>
</insert>
<!-- 通用查询映射结果 -->
<!--<resultMap id="getDataUserListMap" type="com.huoran.users.entity.res.DataUserInfoResp">
@ -1426,6 +1434,16 @@
AND app_open_id = #{openid}
AND platform_id = 3
</select>
<select id="existsByAccount" resultType="java.lang.Boolean">
SELECT
count(1) > 0
FROM
hr_user_account
WHERE
account = #{account}
</select>
<update id="unbindMobilePhone" parameterType="java.lang.Integer">
UPDATE hr_user_account

@ -1,6 +1,13 @@
<?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.huoran.users.mapper.HrUserInfoMapper">
<insert id="batchInsert" useGeneratedKeys="true" keyProperty="userId">
INSERT INTO hr_user_info (unique_identification, create_time, school_id)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.uniqueIdentification}, #{item.createTime}, #{item.schoolId})
</foreach>
</insert>
<!-- 通用查询映射结果 -->
<!-- <resultMap id="BaseResultMap" type="com.huoran.common.entity.HrUserInfo">

@ -11,5 +11,22 @@
<result column="update_time" property="updateTime"/>
<result column="is_del" property="isDel"/>
</resultMap>
<insert id="batchInsert">
INSERT INTO occupationlab.ol_student(account_id, class_id, create_time, update_time, is_del,school_id) VALUES
<foreach collection="list" item="item" separator=",">
(#{item.id},#{classId},now(),now(),0,#{item.schoolId})
</foreach>
</insert>
<insert id="batchInsertTeachers">
INSERT INTO `occupationlab`.`ol_staff`( `grade_id`, `staff_architecture_id`, `school_id`,
`account_id`, `role_id`, `is_del`)
VALUES
<foreach collection="list" item="item" separator=",">
(#{req.gradeId},#{req.staffArchitectureId},#{req.schoolId},#{item.id},#{req.roleId},0)
</foreach>
</insert>
</mapper>

@ -5,6 +5,7 @@ import com.huoran.common.response.R;
import com.huoran.common.entity.HrUserAccount;
import com.huoran.common.entity.HrUserInfo;
import com.huoran.users.entity.dto.LoginDTO;
import com.huoran.users.entity.req.AddUsersInBatchesReq;
import com.huoran.users.entity.req.AppletCallbackReq;
import com.huoran.users.entity.req.UnbindAccountsReq;
import com.huoran.users.entity.req.WxUserBindingReq;
@ -89,4 +90,8 @@ public interface IHrUserInfoService extends IService<HrUserInfo> {
R forgotPreVerification(String phoneOrEmail,String platform);
R quickRegistration(QuickRegistrationVo quickRegistrationVo);
void generateUsersWithParams(AddUsersInBatchesReq addUsersInBatchesReq);
R checkUserNameOrWorkNumber(String accountId);
}

@ -15,6 +15,7 @@ import com.google.gson.GsonBuilder;
import com.huoran.api.NakadaiClient;
import com.huoran.api.UserClient;
import com.huoran.common.constant.*;
import com.huoran.common.entity.Class;
import com.huoran.common.entity.HrUserAccount;
import com.huoran.common.entity.HrUserInfo;
import com.huoran.common.exception.CustomException;
@ -42,6 +43,7 @@ import com.huoran.users.utils.poi.ExcelExportUtil;
import com.huoran.users.utils.poi.ExceptionCast;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.ApiModelProperty;
import lombok.SneakyThrows;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
@ -111,6 +113,10 @@ public class HrUserInfoServiceImpl extends ServiceImpl<HrUserInfoMapper, HrUserI
@Autowired
private RoleMapper roleMapper;
@Autowired
private StudentMapper studentMapper;
@Autowired
private UserRoleMapper userRoleMapper;
@ -680,7 +686,7 @@ public class HrUserInfoServiceImpl extends ServiceImpl<HrUserInfoMapper, HrUserI
/**
* 更新用户信息返回登录token
* */
*/
public LoginDTO updateUserInformation(HrUserAccount userAccount) {
if (userAccount.getCustomerId() == null && StringUtils.isEmpty(userAccount.getPhone())) {
throw new CustomException(ExceptionEnum.NO_BIND_PHONE);
@ -852,6 +858,7 @@ public class HrUserInfoServiceImpl extends ServiceImpl<HrUserInfoMapper, HrUserI
/**
* 账号信息效验生成token
*
* @return token
*/
public LoginDTO queryAccountInfo(HrUserAccount userAccount, boolean verify) {
@ -1093,6 +1100,7 @@ public class HrUserInfoServiceImpl extends ServiceImpl<HrUserInfoMapper, HrUserI
/**
* 根据code获取用户openid
*
* @param code 微信登录code
* @return OpenId
* @throws Exception
@ -1218,6 +1226,137 @@ public class HrUserInfoServiceImpl extends ServiceImpl<HrUserInfoMapper, HrUserI
}
}
@Transactional(rollbackFor = Exception.class)
public void generateUsersWithParams(AddUsersInBatchesReq req) {
try {
// 生成用户信息
long baseTime = System.currentTimeMillis();
List<HrUserInfo> batchUsers = new ArrayList<>();
List<HrUserAccount> batchAccounts = new ArrayList<>();
for (int i = 1; i <= req.getNumberOfUsers(); i++) {
String uniqueIdentification = generateUniqueIdentification(baseTime, i);
Date createTime = new Date();
// 创建用户信息对象
HrUserInfo userInfo = new HrUserInfo();
userInfo.setUniqueIdentification(uniqueIdentification);
userInfo.setCreateTime(createTime);
userInfo.setSchoolId(Integer.valueOf(req.getSchoolId()));
batchUsers.add(userInfo);
if (i % req.getBatchSize() == 0) { // 每 batchSize 条记录执行一次批量插入
batchInsertUsersAndAccounts(batchUsers, batchAccounts, req);
batchUsers.clear();
batchAccounts.clear();
}
}
// 处理剩余的用户信息
if (!batchUsers.isEmpty()) {
batchInsertUsersAndAccounts(batchUsers, batchAccounts, req);
}
System.out.println("成功生成 " + req.getNumberOfUsers() + " 个用户");
} catch (Exception e) {
e.printStackTrace();
throw e; // 抛出异常以触发事务回滚
}
}
@Override
public R checkUserNameOrWorkNumber(String accountId) {
QueryWrapper<HrUserAccount> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("id", accountId);
HrUserAccount hrUserAccount = hrUserAccountMapper.selectOne(queryWrapper);
if (hrUserAccount == null) {
return R.error("用户账号不存在");
}
QueryWrapper<HrUserInfo> queryWrapper1 = new QueryWrapper<>();
queryWrapper1.eq("user_id", hrUserAccount.getUserId());
HrUserInfo hrUserInfo = hrUserInfoMapper.selectOne(queryWrapper1);
if (hrUserInfo == null) {
return R.error("用户信息不存在");
}
boolean hasName = hrUserInfo.getUserName() != null && !hrUserInfo.getUserName().isEmpty();
return R.ok().put("hasName", hasName).put("userName", hrUserInfo.getUserName())
.put("workNumber", hrUserAccount.getAccount());
}
private void batchInsertUsersAndAccounts(List<HrUserInfo> batchUsers, List<HrUserAccount> batchAccounts, AddUsersInBatchesReq req) {
// 批量插入用户信息
baseMapper.batchInsert(batchUsers);
// 生成账户信息
for (HrUserInfo userInfo : batchUsers) {
int userId = userInfo.getUserId();
String password = "42b52043241e27e1d91c117e184f4353"; // 实际应用中应使用安全方式生成随机密码
int isEnable = 1;
Date createTime = new Date();
String account = formatAccount(userId);
// 检查是否已经存在相同的 account
if (userAccountMapper.existsByAccount(account)) {
throw new RuntimeException("账户 " + account + " 已经存在");
}
// 创建账户信息对象
HrUserAccount userAccount = new HrUserAccount();
userAccount.setUserId(userId);
userAccount.setPassword(password);
userAccount.setRoleId(String.valueOf(0));
userAccount.setIsEnable(isEnable);
userAccount.setCreateTime(createTime);
userAccount.setAccount(account);
userAccount.setPlatformId(req.getPlatformId());
userAccount.setType(req.getType());
userAccount.setSchoolId(req.getSchoolId());
batchAccounts.add(userAccount);
}
// 批量插入账户信息
userAccountMapper.batchInsert(batchAccounts);
if (req.getType() == 1) {//如果为学生端,还需要加入到学生表中
//批量新增到学生表
studentMapper.batchInsert(batchAccounts, req.getClassId());
} else if (req.getType() == 0) {
//批量新增到教师
if (req.getStaffArchitectureId() == null || req.getGradeId() == null || req.getRoleId() == null) {
throw new RuntimeException("参数错误");
}
studentMapper.batchInsertTeachers(batchAccounts, req);
List<Integer> roleIds = new ArrayList<>();
roleIds.add(Integer.valueOf(req.getRoleId()));
List<Integer> accountIds = batchAccounts.stream().map(HrUserAccount::getId).collect(Collectors.toList());
for (Integer accountId : accountIds) {
userClient.rolePermissionService(accountId, roleIds, null); //账号赋予角色
}
}
}
private String generateUniqueIdentification(long baseTime, int sequence) {
return String.valueOf(baseTime * 1000 + sequence);
}
private String formatAccount(int userId) {
return String.format("%010d", 9000000000L + userId);
}
@Override
public R forgotPassword(ForgotPasswordVo forgotPasswordVo) {
List<HrUserAccount> hrUserAccounts = null;
@ -1532,6 +1671,7 @@ public class HrUserInfoServiceImpl extends ServiceImpl<HrUserInfoMapper, HrUserI
/**
* 参数以raw的方式做post请求
*
* @param url
* @param stringJson
* @param headers
@ -1646,6 +1786,4 @@ public class HrUserInfoServiceImpl extends ServiceImpl<HrUserInfoMapper, HrUserI
}
}

@ -0,0 +1,155 @@
/*
package com.huoran.users.utils;
import java.sql.*;
import java.util.Date;
public class UserGenerator {
private static final String DB_URL = "jdbc:mysql://localhost:3306/data?serverTimezone=UTC";
private static final String USER = "root";
private static final String PASS = "123456";
public static void main(String[] args) {
int numberOfUsers = 9900; // 默认生成的用户数量
int batchSize = 1000; // 默认批量插入的数量
if (args.length > 0) {
try {
numberOfUsers = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Invalid number of users specified. Using default value: 1000");
}
}
if (args.length > 1) {
try {
batchSize = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.err.println("Invalid batch size specified. Using default value: 1000");
}
}
generateUsers(numberOfUsers, batchSize);
}
public static void generateUsers(int numberOfUsers, int batchSize) {
Connection conn = null;
PreparedStatement pstmtUserInfo = null;
PreparedStatement pstmtUserAccount = null;
try {
// 连接数据库
conn = DriverManager.getConnection(DB_URL, USER, PASS);
conn.setAutoCommit(false); // 开启事务
// 查询上次最后一条记录的主键ID
int lastUserId = getLastUserId(conn);
// 准备 SQL 语句
String sqlUserInfo = "INSERT INTO hr_user_info (unique_identification, create_time, school_id) VALUES (?, ?, 1)";
String sqlUserAccount = "INSERT INTO hr_user_account (user_id, password, role_id, is_enable, create_time, account) VALUES (?, ?, ?, ?, ?, ?)";
pstmtUserInfo = conn.prepareStatement(sqlUserInfo, Statement.RETURN_GENERATED_KEYS);
pstmtUserAccount = conn.prepareStatement(sqlUserAccount, Statement.RETURN_GENERATED_KEYS);
// 生成用户信息
long baseTime = System.currentTimeMillis();
for (int i = 1; i <= numberOfUsers; i++) {
String uniqueIdentification = generateUniqueIdentification(baseTime, i);
Date createTime = new Date();
// 插入用户信息
pstmtUserInfo.setString(1, uniqueIdentification);
pstmtUserInfo.setTimestamp(2, new java.sql.Timestamp(createTime.getTime()));
pstmtUserInfo.addBatch();
if (i % batchSize == 0) { // 每 batchSize 条记录执行一次批量插入
pstmtUserInfo.executeBatch();
pstmtUserInfo.clearBatch(); // 清空批处理中的对象
}
}
// 执行剩余的批量插入
pstmtUserInfo.executeBatch();
pstmtUserInfo.clearBatch(); // 清空批处理中的对象
// 获取新生成的用户 ID 并生成账户信息
String selectUserIdSql = "SELECT user_id FROM hr_user_info WHERE user_id > ? ORDER BY user_id";
try (PreparedStatement selectUserIdStmt = conn.prepareStatement(selectUserIdSql)) {
selectUserIdStmt.setInt(1, lastUserId);
try (ResultSet rs = selectUserIdStmt.executeQuery()) {
while (rs.next()) {
int userId = rs.getInt("user_id");
String password = "e10adc3949ba59abbe56e057f20f883e"; // 实际应用中应使用安全方式生成随机密码
String roleId = "0";
int isEnable = 1;
Date createTime = new Date();
String account = formatAccount(userId);
// 插入账户信息
pstmtUserAccount.setInt(1, userId);
pstmtUserAccount.setString(2, password);
pstmtUserAccount.setString(3, roleId);
pstmtUserAccount.setInt(4, isEnable);
pstmtUserAccount.setTimestamp(5, new java.sql.Timestamp(createTime.getTime()));
pstmtUserAccount.setString(6, account);
pstmtUserAccount.addBatch();
if ((userId - lastUserId) % batchSize == 0) { // 每 batchSize 条记录执行一次批量插入
pstmtUserAccount.executeBatch();
pstmtUserAccount.clearBatch(); // 清空批处理中的对象
}
}
// 执行剩余的批量插入
pstmtUserAccount.executeBatch();
pstmtUserAccount.clearBatch(); // 清空批处理中的对象
}
}
// 提交事务
conn.commit();
System.out.println("成功生成 " + numberOfUsers + " 个用户");
} catch (SQLException e) {
e.printStackTrace();
if (conn != null) {
try {
conn.rollback(); // 回滚事务
} catch (SQLException ex) {
ex.printStackTrace();
}
}
} finally {
// 关闭资源
try {
if (pstmtUserAccount != null) pstmtUserAccount.close();
if (pstmtUserInfo != null) pstmtUserInfo.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static int getLastUserId(Connection conn) throws SQLException {
String sql = "SELECT COALESCE(MAX(user_id), 0) AS last_user_id FROM hr_user_info";
try (PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
return rs.getInt("last_user_id");
}
}
return 0;
}
private static String generateUniqueIdentification(long baseTime, int sequence) {
return String.valueOf(baseTime * 1000 + sequence);
}
private static String formatAccount(int userId) {
return String.format("%010d", 9000000000L + userId);
}
}
*/

@ -0,0 +1,171 @@
/*
package com.huoran.users.utils;
import java.sql.*;
import java.util.Date;
public class UserGenerator1 {
private static final String DB_URL = "jdbc:mysql://localhost:3306/data?serverTimezone=UTC";
private static final String USER = "root";
private static final String PASS = "123456";
public static void main(String[] args) {
int numberOfUsers = 10001; // 默认生成的用户数量
int batchSize = 1000; // 默认批量插入的数量
String role_id = "0"; // 默认角色ID
String school_id = "1"; // 默认学校ID
String platform_id = "1"; // 默认平台ID
if (args.length > 0) {
try {
numberOfUsers = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Invalid number of users specified. Using default value: 9900");
}
}
if (args.length > 1) {
try {
batchSize = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
System.err.println("Invalid batch size specified. Using default value: 1000");
}
}
if (args.length > 2) {
role_id = args[2];
}
if (args.length > 3) {
school_id = args[3];
}
if (args.length > 4) {
platform_id = args[4];
}
generateUsersWithParams(numberOfUsers, batchSize, role_id, school_id, platform_id);
}
public static void generateUsersWithParams(int numberOfUsers, int batchSize, String role_id, String school_id, String platform_id) {
Connection conn = null;
PreparedStatement pstmtUserInfo = null;
PreparedStatement pstmtUserAccount = null;
try {
// 连接数据库
conn = DriverManager.getConnection(DB_URL, USER, PASS);
conn.setAutoCommit(false); // 开启事务
// 查询上次最后一条记录的主键ID
int lastUserId = getLastUserId(conn);
// 准备 SQL 语句
String sqlUserInfo = "INSERT INTO hr_user_info (unique_identification, create_time, school_id) VALUES (?, ?, ?)";
String sqlUserAccount = "INSERT INTO hr_user_account (user_id, password, role_id, is_enable, create_time, account, platform_id) VALUES (?, ?, ?, ?, ?, ?, ?)";
pstmtUserInfo = conn.prepareStatement(sqlUserInfo, Statement.RETURN_GENERATED_KEYS);
pstmtUserAccount = conn.prepareStatement(sqlUserAccount, Statement.RETURN_GENERATED_KEYS);
// 生成用户信息
long baseTime = System.currentTimeMillis();
for (int i = 1; i <= numberOfUsers; i++) {
String uniqueIdentification = generateUniqueIdentification(baseTime, i);
Date createTime = new Date();
// 插入用户信息
pstmtUserInfo.setString(1, uniqueIdentification);
pstmtUserInfo.setTimestamp(2, new java.sql.Timestamp(createTime.getTime()));
pstmtUserInfo.setString(3, school_id);
pstmtUserInfo.addBatch();
if (i % batchSize == 0) { // 每 batchSize 条记录执行一次批量插入
pstmtUserInfo.executeBatch();
pstmtUserInfo.clearBatch(); // 清空批处理中的对象
}
}
// 执行剩余的批量插入
pstmtUserInfo.executeBatch();
pstmtUserInfo.clearBatch(); // 清空批处理中的对象
// 获取新生成的用户 ID 并生成账户信息
String selectUserIdSql = "SELECT user_id FROM hr_user_info WHERE user_id > ? ORDER BY user_id";
try (PreparedStatement selectUserIdStmt = conn.prepareStatement(selectUserIdSql)) {
selectUserIdStmt.setInt(1, lastUserId);
try (ResultSet rs = selectUserIdStmt.executeQuery()) {
while (rs.next()) {
int userId = rs.getInt("user_id");
String password = "e10adc3949ba59abbe56e057f20f883e"; // 实际应用中应使用安全方式生成随机密码
int isEnable = 1;
Date createTime = new Date();
String account = formatAccount(userId);
// 插入账户信息
pstmtUserAccount.setInt(1, userId);
pstmtUserAccount.setString(2, password);
pstmtUserAccount.setString(3, role_id);
pstmtUserAccount.setInt(4, isEnable);
pstmtUserAccount.setTimestamp(5, new java.sql.Timestamp(createTime.getTime()));
pstmtUserAccount.setString(6, account);
pstmtUserAccount.setString(7, platform_id);
pstmtUserAccount.addBatch();
if ((userId - lastUserId) % batchSize == 0) { // 每 batchSize 条记录执行一次批量插入
pstmtUserAccount.executeBatch();
pstmtUserAccount.clearBatch(); // 清空批处理中的对象
}
}
// 执行剩余的批量插入
pstmtUserAccount.executeBatch();
pstmtUserAccount.clearBatch(); // 清空批处理中的对象
}
}
// 提交事务
conn.commit();
System.out.println("成功生成 " + numberOfUsers + " 个用户");
} catch (SQLException e) {
e.printStackTrace();
if (conn != null) {
try {
conn.rollback(); // 回滚事务
} catch (SQLException ex) {
ex.printStackTrace();
}
}
} finally {
// 关闭资源
try {
if (pstmtUserAccount != null) pstmtUserAccount.close();
if (pstmtUserInfo != null) pstmtUserInfo.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static int getLastUserId(Connection conn) throws SQLException {
String sql = "SELECT COALESCE(MAX(user_id), 0) AS last_user_id FROM hr_user_info";
try (PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
return rs.getInt("last_user_id");
}
}
return 0;
}
private static String generateUniqueIdentification(long baseTime, int sequence) {
return String.valueOf(baseTime * 1000 + sequence);
}
private static String formatAccount(int userId) {
return String.format("%010d", 9000000000L + userId);
}
}
*/
Loading…
Cancel
Save