java - 将 XML 中的不同值插入数据库表
问题描述
我有如下 XML:
<employee>
<code>13</code>
<label>Admin</label>
</employee>
<employee>
<code>13</code>
<label>Admin</label>
</employee>
<employee>
<code>09</code>
<label>Logistics</label>
</employee>
在我的 Oracle 数据库中,我有 2 列,即 CODE1、CODE2。应该像 CODE1= 13 和 CODE2= 09 一样插入数据。
但是,目前发生的是 CODE1= 13 和 CODE2= 13。并且 09 没有插入数据库。
它只存储前 2 个值而忽略其余值。 我的要求是,重复值只能在 DB 中插入一次。
预期结果: CODE1= 13,CODE2= 09
以下是我的java代码:
for (int i = 0; i < 2; i++) {
final int count = i + 1;
String code = null;
final Emploi[] employee = tabLieuTrav.getEmployee();
code = employee[i].getCode();
if (code != null) {
mapParam.addParamValue(CODE + count,
code);
} else {
mapParam.addParamValue(CODE + count, null,
Types.VARCHAR);
}
getCode() 从 tag 中返回值(例如 13)。
提前致谢。
解决方案
尝试以下解决方案,
首先,您应该创建一个 Employee 类,包括如下的 withhasCode()
和方法,equals()
public class Employee {
private int code;
private String lable;
public Employee(int code, String lable) {
super();
this.code = code;
this.lable = lable;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getLable() {
return lable;
}
public void setLable(String lable) {
this.lable = lable;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + code;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (code != other.code)
return false;
return true;
}
}
以上hasCode()
和equals()
方法都是eclipse ide生成的。您可以像这样手动创建这些方法,
@Override
public boolean equals(Object obj) {
if (obj instanceof Employee) {
return Objects.equals(code, ((Employee) obj).code);
}
return false;
}
@Override
public int hashCode() {
return this.code;
}
equals 方法:指示其他对象是否“等于”这个对象。了解更多信息
hashCode 方法:返回对象的哈希码值。支持这种方法是为了有利于哈希表,例如 HashMap 提供的那些。了解更多信息
然后,将employee
数组添加到 ArrayList。因为下面提到的方法描述了如何从 ArrayList 中获取不同的值。
Emploi[] employee = tabLieuTrav.getEmployee();
List<Employee> empList = new ArrayList(Arrays.asList(employee));
然后,您可以使用以下方法之一从 ArrayList ( empList
)中删除重复值
方法一,使用 Set(不包含重复元素的集合)从 ArrayList 中删除重复项以获取更多信息
HashSet<Employee> uniqueEmployee = new HashSet(empList);
方法二,使用 java 8 流不同方法(从集合中返回不同元素)从 ArrayList 中删除重复项以获取更多信息
List<Employee> uniqueEmployee = empList..stream().distinct().collect(Collectors.toList();
最后,您可以uniqueEmployee
按如下方式使用集合,
for (Employee employee : uniqueEmployee) {
code = employee.getCode();
if (code != null) {
mapParam.addParamValue(CODE + count, code);
} else {
mapParam.addParamValue(CODE + count, null, Types.VARCHAR);
}
}
推荐阅读
- r - 使用临时文件夹通过 testthat 运行测试
- c - 为什么编译器无法检测到我的代码中的减号?
- hadoop - 未能放置足够的副本:预期大小为 1,但只能选择 0 个存储类型
- kotlin - 改造查询参数添加apiKey
- c - 在“header.h”文件中声明了一个自引用结构并尝试在“main.c”中定义它,这会导致错误
- .net - .Net应用程序在调试时提示登录浏览器
- c# - 如何在 WPF 页面中实现 IDataErrorInfo(部分类)
- node.js - Express JS - 从 REST 调用加载数据并在应用程序启动时设置为应用程序变量
- php - 将 mailchimp 与 CRM 集成
- quill - QuillJs 处理大文档时速度很慢